Reputation: 643
I have this code below to copy VBA codes from one word document to another (I'm using C#). It works for modules however I can't seem to get it to work with userforms.
VBComponent sourceVBC = GetSourceDocVB();
VBComponent targetVBC = document.VBProject.VBComponents.Add(sourceVBC.Type);
string codes = sourceVBC.CodeModule.get_Lines(1, sourceVBC.CodeModule.CountOfLines);
targetVBC.CodeModule.AddFromString(codes);
targetVBC.Name = sourceVBC.Name;
Yes, the userform is copied to the target document but its fields are not. Like if it contains labels and textboxes. Those fields are not copied. Am I missing something here?
Upvotes: 1
Views: 1163
Reputation: 1022
Yes, you are missing something. Forms are not defined in the code file only, but need a binary file too. You don't tell anything about the way the source files are generated. Normally, in VBA, you use the "Export" statement of the VBComponent object. Of course one can do it manually by going to the VBA Editor in Word, right-clicks the project component and selects "Export". If you have a look into the export folder, you'll see that a form is saved as two files "Form1.frm" (containing the code) and "Form1.frx" (containing binary form data, as labels and other stuff). In the other project, you can use maually the File, Import function, which takes care of the binary definition if you import a form.
In VBA, you may use something like this to export from a project:
For Each vbC In ActiveDocument.VBProject.VBComponents
Select Case vbC.Type
Case vbext_ct_StdModule
strVbcExt = ".bas"
Case vbext_ct_ClassModule
strVbcExt = ".cls"
Case vbext_ct_MSForm
strVbcExt = ".frm"
Case Else
End Select
strvbCName = vbC.Name
strFilename = strPath & "\" & strvbCName & strVbcExt
vbC.Export strFilename
(omitted the rest)
And to import you'll use
ActiveDocument.VBProject.VBComponents.Import strFilename
Upvotes: 3