0

Is it possible to create a macro-enabled word file (.docm) using C# and Microsoft.Office.Interop.Word library?

An example of a macro I need would be:

Private Sub CheckBox1_Click()
    If CheckBox1.Value = False Then
        Paragraph1.Value = "aaa"
    End If
End Sub

This macro would not be run by C#, but rather when a user opens the word document and clicks a CheckBox.

Essentially, I'm trying to automatically generate a couple of .docm word templates without having to manage every file individually using the Visual Basic for Applications in Word. Is this possible in C# or there some other library I can use in Visual Basic (using Visual Studio IDE)?

Any replies would be greatly appreciated as I haven't been able to find anything about creating .docm files directly in C#.

Shams Tech
  • 105
  • 8
  • 1
    You could use automation of Word to create the document. See http://www.cpearson.com/excel/vbe.aspx or https://stackoverflow.com/questions/41478498/insert-and-run-macro-into-word-using-interop-in-c-sharp – Tim Williams Jun 07 '21 at 15:13
  • Why not simply, in Word, create a macro-enabled template. You can set it as a Global template. Note that to work well, you will want an AutoExec / AutoNew / AutoOpen that has sets the option to one click. For samples, see my Check-Box Add-In http://www.addbalance.com/word/download.htm#CheckboxAddIn. I realize that it is dated, created around 2000, but you should get some ideas from it. The code is not locked. – Charles Kenyon Jun 07 '21 at 15:53
  • @TimWilliams So I'd have to write the macro as a raw string in vb and then add it in C# with the AddFromString function? Also, how would I give my checkbox the name "CheckBox1" in order for the "CheckBox1_Click" event to apply to it? – user689123 Jun 08 '21 at 04:19
  • @CharlesKenyon The goal is to create individual components for the word documents in C# so that I can programmatically produce word documents with these components. For example, if I end up modify the checkbox that I'm creating above, I'd just have to change the checkbox code in one place and re-generate all the word docs using C#, rather than opening each .docm file individually and modifying the code in VBA. – user689123 Jun 08 '21 at 04:23
  • You can store your macros in a text/config file in whatever format you like. You can name your checkbox when you add it. – Tim Williams Jun 08 '21 at 04:30

0 Answers0