4

我正在使用 VBA 代码在 excel 表中插入一个 ActiveX 控件标签。现在插入按钮后,我试图插入点击事件代码,但它不起作用。下面是代码:

Public Function AddButton(strSheetName, counter)
Dim btn As OLEObject
Dim cLeft, cTop, cWidth, cHeight
Dim CodeModule As Object
    With Worksheets(strSheetName).Range("J" & (6 + counter))
        cLeft = .Left + 1
        cTop = .Top + 1
        cWidth = .Width - 2
        cHeight = .Height - 2
    End With
    With Worksheets(strSheetName)
        Set btn = .OLEObjects.Add(ClassType:="Forms.Label.1", Link:=True, DisplayAsIcon:=True, Left:=cLeft, Top:=cTop, Width:=cWidth, Height:=cHeight)
    End With
    btn.Object.Caption = "Add New"
    btn.Name = Left(strSheetName, 3) & counter
    Set CodeModule = ActiveWorkbook.VBProject.VBComponents.VBE.ActiveCodePane.CodeModule
    CodeModule.InsertLines CodeModule.CreateEventProc("Click", btn.Name) + 1, vbTab & "MsgBox ""Hello world"""
End Function

按钮正在插入,但单击事件代码不起作用。当我点击什么都没有发生。这个函数也在循环中被调用。第一次添加按钮,然后一旦尝试添加点击事件代码,循环就会终止,这意味着存在错误。

有什么帮助吗?

提前致谢。

4

1 回答 1

3

我相信这是你最后一个问题的延续。

这是你正在尝试的吗?

Option Explicit

Sub Sample()
    Dim i As Long

    For i = 1 To 5
        AddButton "Sheet1", i
    Next i
End Sub

Public Sub AddButton(strSheetName As String, counter As Long)
    Dim btn As OLEObject
    Dim cLeft, cTop, cWidth, cHeight

    With Worksheets(strSheetName).Range("J" & (6 + counter))
        cLeft = .Left
        cTop = .Top
        cWidth = .Width
        cHeight = .Height
    End With
    With Worksheets(strSheetName)
        Set btn = .OLEObjects.Add(ClassType:="Forms.Label.1", Link:=True, _
        DisplayAsIcon:=False, Left:=cLeft, Top:=cTop, Width:=cWidth, _
        Height:=cHeight)
    End With
    btn.Object.Caption = "Add New"

    btn.Name = Left(strSheetName, 3) & counter

    With ActiveWorkbook.VBProject.VBComponents( _
    ActiveWorkbook.Worksheets(strSheetName).CodeName).CodeModule
        .InsertLines Line:=.CreateEventProc("Click", btn.Name) + 1, _
        String:=vbCrLf & _
        "MsgBox ""Hello world"""
    End With
End Sub

跟进

是的,从整个 Excel 项目的特定工作表中清除代码。这就是要求 – user1269291 54 秒前

Option Explicit

Sub Sample()
    Dim strSheetName As String

    strSheetName = "Sheet1"

    With ActiveWorkbook.VBProject.VBComponents( _
    ActiveWorkbook.Worksheets(strSheetName).CodeName).CodeModule
        .DeleteLines 1, .CountOfLines
    End With
End Sub
于 2012-05-17T10:15:01.093 回答