将事件处理程序分配给在VBA中动态创建的用户窗体上的控件

我在Internet上发现了很多资源,这些资源几乎可以完成我想做的事情,但不完全是我的工作。我有一个命名范围“ daylist”。对于dayList中的每一天,我想在用户表单上创建一个按钮来运行当天的宏。我能够动态添加按钮,但不知道如何将daycell.text从命名范围传递到按钮,事件处理程序和宏:S这里,我必须创建用户表单的代码:


Sub addLabel()

ReadingsLauncher.Show vbModeless

Dim theLabel As Object

Dim labelCounter As Long

Dim daycell As Range

Dim btn As CommandButton

Dim btnCaption As String



For Each daycell In Range("daylist")

    btnCaption = daycell.Text

    Set theLabel = ReadingsLauncher.Controls.Add("Forms.Label.1", btnCaption, True)

    With theLabel

        .Caption = btnCaption

        .Left = 10

        .Width = 50

        .Top = 20 * labelCounter

    End With


    Set btn = ReadingsLauncher.Controls.Add("Forms.CommandButton.1", "runButton", True)

    With btn

        .Caption = "Run Macro for " & btnCaption

        .Left = 80

        .Width = 80

        .Top = 20 * labelCounter

    '   .OnAction = "btnPressed"

    End With


    labelCounter = labelCounter + 1

Next daycell


End Sub

为了解决上述问题,我目前提示用户输入他们想运行的日期(例如Day1)并将其传递给宏,然后它可以工作:


Sub B45runJoinTransactionAndFMMS()



loadDayNumber = InputBox("Please type the day you would like to load:", Title:="Enter Day", Default:="Day1")


Call JoinTransactionAndFMMS(loadDayNumber)


End Sub


Sub JoinTransactionAndFMMS(loadDayNumber As String)

xDayNumber = loadDayNumber


Sheets(xDayNumber).Activate

-Do stuff


End Sub

因此,对于我的每个runButton,它都需要显示daycell.text,并运行一个使用相同文本作为参数的宏,以选择要执行其工作的工作表。


任何帮助都是极好的。我见过响应,它们动态地编写了VBA代码来处理宏,但是我相信一定可以通过传递参数来更好地完成它,只是不确定如何做到。提前谢谢了!


不负相思意
浏览 982回答 3
3回答

哆啦的时光机

捕获单击工作表的示例。将其放在工作表模块中:Private Sub Worksheet_SelectionChange(ByVal Target As Range)  ' e.g., range(A1:E1) is clicked  If Not Application.Intersect(Target, Range("A1:E1")) Is Nothing Then    MsgBox "You clicked " & Target.Address  End IfEnd Sub

回首忆惘然

有用!测试我使用的代码:(Sub intersectCallingMacro() Range("D8").Select 'used for testing only Set target = ActiveCell If Not Application.Intersect(target, Range("A1:M100")) Is Nothing Then Call testIntersect(ActiveCell.Value) End If End Sub Sub testIntersect(dayString As String) Dim xDayString As String xDayString = dayString Sheets(xDayString).Activate End Sub 为代码格式化道歉)将单元值作为参数传递给宏。惊人!
打开App,查看更多内容
随时随地看视频慕课网APP