如何从另一个 macro/script 访问文件中宏的内容?

How to access the contents of a macro in a file from another macro/script?

作为数据迁移过程的一部分,我需要一个 script/macro 来访问源位置中的所有文件并检查内部 linked 文档,以便那些 link 可以重新建立post迁移(已经完成)。除了直接 links,如果一个文件有一个试图访问另一个文件的宏,那么 link 也应该被恢复 post 迁移(需要一个解决方案)。

所以基本上,有没有一种方法可以从另一个 script/macro 访问文件中宏的内容(检查第一个宏试图访问的文档,这样它甚至可以工作 post迁移)?

是的。您实际上可以通过对 Visual Basic 编辑器 (VBE) 本身进行编程来读取模块(或任何 VBA 项目组件)的内容。您可以按照以下步骤操作。

  1. 添加对 VBA 扩展库的引用

    Microsoft Visual Basic For Applications Extensibility 5.3

  2. 一旦成功,您就可以编写代码以从另一个工作簿中的另一个模块或项目中检索代码行。像下面这样打印标准模块中的代码:

    Dim VBProj As VBIDE.VBProject
    Dim VBComp As VBIDE.VBComponent
    Dim VBCodeMod As VBIDE.CodeModule
    
    Dim wb As Workbook, i As Integer
    
    Set wb = ThisWorkbook '/* or any target workbook */
    '/* You can actually create a loop which opens all workbooks in a directory */
    
    Set VBProj = wb.VBProject
    
    '/* For simplicity sake, this prints all codes in a Standard Module */
    For Each VBComp In VBProj.VBComponents
        If VBComp.Type = vbext_ct_StdModule Then
            Set VBCodeMod = VBComp.CodeModule
            With VBCodeMod
                For i = 1 To .CountOfLines
                    '/* This prints the lines in the module */
                    Debug.Print .Lines(i, 1)
                    '/* You can transfer this instead somewhere */
                Next
            End With
        End If
    Next
    
  3. 如果您只需要特定的行,您可以使用Find方法:

    Dim VBProj As VBIDE.VBProject
    Dim VBComp As VBIDE.VBComponent
    Dim VBCodeMod As VBIDE.CodeModule
    
    Dim wb As Workbook, IsFound As Boolean
    Dim StartLine As Long, EndLine As Long, StartCol As Long, EndCol As Long
    
    Set wb = ThisWorkbook
    Set VBProj = wb.VBProject
    
    For Each VBComp In VBProj.VBComponents
        If VBComp.Type = vbext_ct_StdModule Then
            Set VBCodeMod = VBComp.CodeModule
            With VBCodeMod
    
                StartLine = 1
                EndLine = .CountOfLines
                StartCol = 1
                EndCol = 255
    
                '/* Below finds a specific pattern, e.g. directory */
                '/* patternsearch argument set to true */
                IsFound = .Find("C:\*", StartLine, StartCol, _
                    EndLine, EndCol, False, False, True)
    
                Do Until IsFound = False
                    Debug.Print .Lines(StartLine, 1) '/* Prints the found pattern */
                    EndLine = .CountOfLines
                    StartCol = EndCol + 1
                    EndCol = 255
                    IsFound = .Find("C:\*", StartLine, StartCol, _
                        EndLine, EndCol, False, False, True)
                Loop
            End With
        End If
    Next
    

不确定这是否回答了您的具体问题,但希望这能让您入门。
顺便说一句,重要勾选信任访问VBA 项目对象模型 开发人员宏设置 下的 VBA 项目对象模型 来完成这项工作。

您可以在 开发人员选项卡 > 代码 > 宏安全.
下找到以上内容 当然,项目应该解锁