3

Can we read scripts or lines of code to a module in ? Like we have the include function in .

For example:

We store this in Excel somewhere and call the range as xyz

line 1 of code
line 2 of code
line 3 of code

Then while running a macro we call this like

Sub my_macro()
  xyz
End Sub

Basically I want to run a few lines of code repetitively but don't want to create another macro and pass the parameters.

4

1 回答 1

4

这可以使用 Microsoft Visual Basic for Applications Extensibility 5.3 (VBIDE) 库来完成。CPearson.com上有一些很好的例子。我通常在开发时使用它来插入代码片段。我个人对执行存储在 Excel 表中的代码感到不舒服,但我对此进行了测试,它确实有效。

我的工作表:

  A
1 MsgBox "I'm a test."
2 MsgBox "So am I."

我设置了一个空子程序,然后我们将从 Excel 表中插入该子程序。

Private Sub ProcToModify()

End Sub

以及将代码实际插入的子程序ProcToModify

Sub ModifyProcedure()
        Dim VBProj As VBIDE.VBProject
        Dim VBComp As VBIDE.VBComponent
        Dim CodeMod As VBIDE.CodeModule
        Dim StartLine As Long
        Dim NumLines As Long
        Dim ProcName As String

        Set VBProj = ActiveWorkbook.VBProject
        Set VBComp = VBProj.VBComponents("Module1") ' specify module to modify
        Set CodeMod = VBComp.CodeModule

        Dim ws As Worksheet
        Dim rng As Range
        Dim cell As Range

        Set ws = ThisWorkbook.ActiveSheet 'change this accordingly
        Set rng = ws.Range("A1:A2") 'and this

        For Each cell In rng
            ProcName = "ProcToModify"
            With CodeMod
                StartLine = .ProcStartLine(ProcName, vbext_pk_Proc)
                NumLines = .ProcCountLines(ProcName, vbext_pk_Proc)
                .InsertLines StartLine + NumLines - 2, cell.Value 'insert each line at the end of the procedure to get them in the correct order.
            End With
        Next cell
End Sub

像这样在运行时调用:

Public Sub main()
    ModifyProcedure
    ProcToModify
End Sub

一大难题: 在运行此代码之前,您需要转到 Excel>>文件>>选项>>信任中心>>信任中心设置>>宏设置并选中“信任访问 VBA 项目对象模型”。

我想这是因为允许访问项目对象是一个相当令人担忧的安全风险。

从我之前链接到的 cpearson.com 网站:

注意:许多基于 VBA 的计算机病毒通过创建和/或修改 VBA 代码进行自我传播。因此,许多病毒扫描程序可能会在没有警告或确认的情况下自动删除引用 VBProject 对象的模块,从而导致永久且无法挽回的代码丢失。有关详细信息,请参阅防病毒软件的文档。

于 2014-05-19T13:13:22.290 回答