VBA - 通过单击特定列

时间:2016-03-17 12:25:53

标签: excel vba excel-vba

我想在VBA中构建一个makro,当我点击特定列中的单元格时会打开一个UserForm,有关详细信息,请查看here

使用此代码(来自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

我可以通过单击单元格A1打开UserForm,但不能通过单击A列中的任何单元格来打开。

我尝试使用此代码解决此问题:

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

它实际上工作正常,但速度很慢,有没有更好的解决方案呢?

2 个答案:

答案 0 :(得分:0)

您可以将.count.column属性与AND一起使用,它将变得如此简单快捷。如果您单击活动工作表上的A列,则以下代码会触发弹出窗口

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

答案 1 :(得分:0)

在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