Home > Net >  Word Forms from C#
Word Forms from C#

Time:08-01

I am using the interop libraries for Word in a C# program. Hence, I have the following using statements:

using Word = Microsoft.Office.Interop.Word;

I figured out how to get the forms in the dotm file I have using the following code:

var wordApp = new Application();
var doc = wordApp.Documents.Add(@"\Sample.dotm");
var project = doc.Application.VBE.VBProjects.Cast<VBA.VBProject>().FirstOrDefault();
var form = project.VBComponents.Cast<VBA.VBComponent>().FirstOrDefault(p=> p.Name == "UserForm1");

However, I have struggled to find the controls on the form (ex. btn1, textbox1, etc.). How do I find the controls? I want to capture the control properties.

CodePudding user response:

Ok, I have this working enough to know I can move forward. That said, I am very curious how it should be done. Here are the code snippets I believe constitute the answer. I am using O365 and a console app (Framework 4.8):

using Word = Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
using Microsoft.Vbe.Interop;            


        var wordApp = new Application();
        var doc = wordApp.Documents.Add(@"X:\repos\Samples\Word\__ABCCompany.dotm");
        doc.Activate();
        var project = doc.Application.VBE.VBProjects.Cast<VBProject>().FirstOrDefault(p => p.Name == "Proj2016");
        var vbComponents = project.VBComponents;
        foreach (VBComponent v in vbComponents)
        {
            var t = v.Type;
            switch (t)
            {
                case vbext_ComponentType.vbext_ct_MSForm:
                    var w = v.DesignerWindow();
                    var cntrls =  v.Designer.Controls;
                    foreach (var c in cntrls)
                    {
                        
                    }
                    break;
                default:
                    continue;
            }
        }

I do not know what the c type is in the var c in cntrls but I will tackle that later. For now, I can see the control and its properties when debugging.

CodePudding user response:

You can enumerate and inspect the controls of a UserForm:

foreach(Control control in form.Controls)
{
    control.Visible = false;
}

MSDN documentation

  • Related