0

参考

我试图通过在 VBE 中的 sheet1 中查找过程语句的行号,然后将代码添加到下一行,将代码(子例程调用)添加到 Sheet1 中的过程。下面的代码试图实现这一点。

' This will search for and modify the appropriate Node#button_Click() subroutine
    With ActiveWorkbook.VBProject.VBComponents("Sheet1").CodeModule
            ProcLineNum = .ProcStartLine("Node" & NumNodes & "Button" & "_Click", 0)
            .InsertLines ProcLineNum + 1, "load_node_form(" & DQUOTE & "Node " & NumNodes & DQUOTE & ")"
    End With

整个子程序如下:

Public Sub Node_Button_Duplication()
'
'Com: Copies and pastes Node 1's button to the appropriate column

Dim shp As Shape
Dim code As String
Dim ProcLineNum As Long
Const DQUOTE = """"

' Copy Node 1 button and paste in appropriate location

    ActiveSheet.Shapes("CommandButton1").Select
    Selection.Copy
    Cells(5, 10 + 7 * (NumNodes - 1) - 1).Select
    ActiveSheet.Paste
    Selection.ShapeRange.IncrementLeft 47.25
    Selection.ShapeRange.IncrementTop -13.5


    Set shp = ActiveSheet.Shapes(Selection.Name)

    With shp.OLEFormat.Object
        .Object.Caption = "Node" & Str(NumNodes)
        .Name = "Node" & NumNodes & "Button"
    End With

' This will search for and modify the appropriate Node#button_Click() subroutine
    With ActiveWorkbook.VBProject.VBComponents("Sheet1").CodeModule
            ProcLineNum = .ProcStartLine("Node" & NumNodes & "Button" & "_Click", 0)
            .InsertLines ProcLineNum + 1, "load_node_form(" & DQUOTE & "Node " & NumNodes & DQUOTE & ")"
    End With

End Sub

该子例程将复制并粘贴一个按钮(“CommandButton1”),重命名它,然后尝试分配一个子例程调用。查找过程的问题是,一旦创建了新按钮,“CommandButton#_Click() 过程不会出现在 VBE 中,直到我从编辑器中选择它,因此当我的代码尝试搜索时会导致错误对于那个程序。

4

1 回答 1

1

这是你正在尝试的吗?

Option Explicit

Public Sub Node_Button_Duplication()
    Dim shp As Shape
    Dim code As String
    Dim ProcLineNum As Long, NumNodes As Long

    Const DQUOTE = """"

    ActiveSheet.Shapes("CommandButton1").Select
    Selection.Copy
    Cells(5, 10 + 7 * (NumNodes - 1) - 1).Select
    ActiveSheet.Paste
    Selection.ShapeRange.IncrementLeft 47.25
    Selection.ShapeRange.IncrementTop -13.5

    Set shp = ActiveSheet.Shapes(Selection.Name)

    With shp.OLEFormat.Object
        .Object.Caption = "Node" & Str(NumNodes)
        .Name = "Node" & NumNodes & "Button"
    End With

    With ActiveWorkbook.VBProject.VBComponents( _
    ActiveWorkbook.Worksheets("Sheet1").CodeName).CodeModule
        .InsertLines Line:=.CreateEventProc("Click", "Node" & NumNodes & "Button") + 1, _
        String:=vbCrLf & _
        "load_node_form(" & DQUOTE & "Node " & NumNodes & DQUOTE & ")"
    End With
End Sub
于 2012-05-18T21:46:48.790 回答