如何在不同的xlsm工作簿中引用VBProject?

时间:2014-07-02 22:10:40

标签: vba excel-vba excel

我需要编写一个宏来创建一个新工作簿test.xlsm并为其第一张工作表(Sheet1)分配一个vb代码。

 Sub AddCode()
        Dim wb As Workbook
        Set wb = Workbooks.Add
        Dim ws As Worksheet
        Set ws = wb.Worksheets(1)

        Dim code As String
        code = "Sub test()" & vbCrLf & MsgBox "Test" & vbCrLf & "End Sub"
        Dim lineCount As Integer

        With wb.VBProject.VBComponents(ws.Name).CodeModule
            lineCount = .CountOfLines
            If lineCount > 0 Then
                .DeleteLines 1, lineCount
            End If
            .AddFromString code
        End With

      wb.Save FileName:="C:\Users\Owner\Desktop\test.xlsm", FileFormat:=52
      wb.Close
    End Sub

我收到subscript out of range错误。我认为我指的是错误的vb项目

(PS:通过"为其分配代码'第一张"我的意思如下:Right Click on the Sheet1 -> View Code -> Paste my code to the Module )

1 个答案:

答案 0 :(得分:2)

您可以将工作簿另存为加载项,然后将其加载到Excel中。然后,您可以从VBE编辑器添加对加载项的引用,并访问functions / subs。

你可以谷歌Chip Pearson的教程,以及其他类似的材料。在这里,他解释了如何操作Visual Basic编辑器以编程方式添加代码等。在您的情况下可能很有用。

参考:http://www.cpearson.com/Excel/VBE.aspx

仅为了便于参考(所有来自Chip Pearson的上述网站)

将模块添加到项目中:

Sub AddModuleToProject()
    Dim VBProj As VBIDE.VBProject
    Dim VBComp As VBIDE.VBComponent

    Set VBProj = ActiveWorkbook.VBProject
    Set VBComp = VBProj.VBComponents.Add(vbext_ct_StdModule)
    VBComp.Name = "NewModule"
End Sub

最重要的是,在模块中添加子程序:

 Sub AddProcedureToModule()
    Dim VBProj As VBIDE.VBProject
    Dim VBComp As VBIDE.VBComponent
    Dim CodeMod As VBIDE.CodeModule
    Dim LineNum As Long
    Const DQUOTE = """" ' one " character

    Set VBProj = ActiveWorkbook.VBProject
    Set VBComp = VBProj.VBComponents("Module1")
    Set CodeMod = VBComp.CodeModule

    With CodeMod
        LineNum = .CountOfLines + 1
        .InsertLines LineNum, "Public Sub SayHello()"
        LineNum = LineNum + 1
        .InsertLines LineNum, "    MsgBox " & DQUOTE & "Hello World" & DQUOTE
        LineNum = LineNum + 1
        .InsertLines LineNum, "End Sub"
    End With
End Sub

另一种方法是简单地执行以下操作

Dim FileNameStr as String, Path as String
' Set these two to the correct strings
Dim wb as Workbook

set wb = workbooks.open(Path & "\" & FileNameString)
Application.Run (wb.Name & "!NameOfYourMacro")

这样你可以运行一个没有参数的宏


当然这只是代码的核心。你仍然需要事后清理,关闭工作簿,或者在打开时将它们设置为只读,等等。但是你得到漂移。