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

问题描述 投票:0回答:1

作为数据迁移过程的一部分,我需要一个脚本/宏来访问源位置中的所有文件,并检查相互链接的文档,以便在迁移后重新建立这些链接(已完成)。除了直接链接,如果文件有一个试图访问另一个文件的宏,那么该链接也应该在迁移后恢复(需要一个解决方案)。

所以基本上,有没有办法从另一个脚本/宏访问文件中的宏的内容(检查第一个宏试图访问的文档,以便它甚至可以在迁移后工作)?

vba excel-vba vbe excel
1个回答
0
投票

是。您可以通过编程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项目对象模型的信任访问权限是很重要的。

enter image description here

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

© www.soinside.com 2019 - 2024. All rights reserved.