VBA - Open a UserForm by clicking anywhere in a sp

2019-09-11 01:30发布

I would like to build a makro in VBA which opens a UserForm when I click in a cell in a specific column, for more details look here.

With this code (from Mr.Burns):

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
       If Selection.Count = 1 Then
           If Not Intersect(Target, Range("A1")) Is Nothing Then
            'name of userform .Show
           End If
       End If
   End Sub

I was able to open the UserForm by clicking in the cell A1, but not by clicking in any cell inside the column A.

I tried to solve this problem with this code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  If Selection.Count = 1 Then
    Dim check As Boolean
    check = True
    If check Then
        Dim i As Long
        For i = 1 To 100000
            If Not Intersect(Target, Range("A" & i)) Is Nothing Then
                UserForm1.Show
                check = False
            End If
        Next
    End If
  End If
End Sub

It actually works fine, but it is very slow, is there any better possibility to solve this?

2条回答
祖国的老花朵
2楼-- · 2019-09-11 01:36

To display the form when a cell is selected in column A:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  ' if target is one cell and in column A
  If Target.Columns.count = 1 And Target.Rows.count = 1 And Target.Column = 1 Then
    UserForm1.Show
  End If
End Sub
查看更多
Explosion°爆炸
3楼-- · 2019-09-11 01:50

You can use .count and .column property together with AND and it will become so much simple and fast. Following code triggers pop-up if u click in column A on active-sheet

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error GoTo errorhandler
If Target.Count = 1 And Target.Column = 1 Then '.count to check if only one cell is selected and .column to check if it is a first column
    'UserForm1.Show
    'Do whatever you want to do here like opening User form
    MsgBox "You clicked in column A"
End If
errorhandler:
End Sub
查看更多
登录 后发表回答