如何创建一个宏,将宏添加到文档列表中的每个文档

时间:2014-07-25 21:31:52

标签: vba ms-word word-vba

我制作了一个宏,我想将其放入一长串word文件中。我想编写一个宏来打开每个文件并将宏添加到它。我没有问题浏览文件,打开它们,保存它们并关闭它们,但是,对于我的生活,我无法弄清楚如何添加宏(在文档中使用宏按钮)。我几乎得到了以下代码。此代码按原样工作,并将带有按钮的MsgBox宏添加到新文档中。这很棒,但是当我添加代码时,代替MsgBox,它显然有太多的换行符存储为字符串......或者其他东西。

Sub Test()
    'Add a command button to a new document
    Dim doc As Word.Document
    Dim shp As Word.InlineShape
    Set doc = Documents.Add

    Set shp = doc.Content.InlineShapes.AddOLEControl(ClassType:="Forms.CommandButton.1")
    shp.OLEFormat.Object.Caption = "Click Here"

    'Add a procedure for the click event of the inlineshape
    '**Note: The click event resides in the This Document module
    Dim sCode As String
    sCode = "Private Sub " & shp.OLEFormat.Object.Name & "_Click()" & vbCrLf & _
            "   MsgBox ""You Clicked the CommandButton""" & vbCrLf & _
            "End Sub"
    doc.VBProject.VBComponents("ThisDocument").CodeModule.AddFromString sCode
End Sub

1 个答案:

答案 0 :(得分:1)

Sub test()    
    Dim FILE_NAME As String
    Set FILE_NAME = "C:\Path\To\Your_Module.bas" 'Export your module here

    Application.VBE.ActiveVBProject.VBComponents.Import (FILE_NAME)
        'Make sure you enable programmatic access in your application to
        'allow programatically adding modules / code

        'Trust Center->Trust Center Settings->Macro Settings-> "Trust Access to VBA Object Model"
End Sub