How to add a button programmatically in VBA next to some sheet cell data?

后端 未结 2 1616
余生分开走
余生分开走 2020-11-29 02:00

I have a function that generates data for say 100 rows (and 2 columns). For each row (in the 3rd column) I need to add a button which, when clicked, brings up a custom modal

2条回答
  •  臣服心动
    2020-11-29 02:12

    Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange event:

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        Dim clickRng As Range
        Dim lastRow As Long
    
        lastRow = Range("A1").End(xlDown).Row
        Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A
    
        If Not Intersect(Target, clickRng) Is Nothing Then
            MyUserForm.Show //Launch custom userform
        End If
    
    End Sub
    

    Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)

提交回复
热议问题