将宏应用于整个列

时间:2017-05-23 05:37:08

标签: excel vba excel-vba

我有一个宏,在运行时会打开文件资源管理器,当用户选择特定路径时,它会在活动单元格上粘贴该路径。这是代码。

Sub CommandButton1_Click()
    With Application.FileDialog(msoFileDialogFolderPicker)
        .InitialFileName = IIf(ActiveCell.Value = "", ActiveWorkbook.Path, ActiveCell.Value)
        .Title = "Please choose a folder"
        .AllowMultiSelect = False
        If .Show = -1 Then ActiveCell.Value = .SelectedItems(1)
    End With
End Sub

现在,我不想将此模块分配给按钮,而是分配给整个列,比如列A,因此每当用户单击A列中的任何行时,宏都会被激活。有什么方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:1)

将其放入要触发文件夹选择的工作表的代码模块中:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Target.Cells.CountLarge = 1 And Target.Cells(1).Column = 1 Then
        With Application.FileDialog(msoFileDialogFolderPicker)
          .InitialFileName = IIf(target.Value = "", _
                          thisWorkbook.Path, target.Value)
          .Title = "Please choose a folder"
          .AllowMultiSelect = False
          If .Show = -1 Then Target.Value = .SelectedItems(1)
        End With
    End If

End Sub

双击:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

    If Target.Cells.CountLarge = 1 And Target.Cells(1).Column = 1 Then
        With Application.FileDialog(msoFileDialogFolderPicker)
          .InitialFileName = IIf(ActiveCell.Value = "", ActiveWorkbook.Path, ActiveCell.Value)
          .Title = "Please choose a folder"
          .AllowMultiSelect = False
          If .Show = -1 Then Target.Value = .SelectedItems(1)
        End With
        Cancel = True '<< prevents going into edit mode
    End If

End Sub