事件点击单元格

时间:2019-04-10 11:55:14

标签: excel vba

我刚刚创建了一个新文件,并放置了数据(A1到A10行),我想知道每次单击单元格A(如果它不为空)时如何从该单元格获取数据(例如:when我单击列A的第三行,这样我就可以得到它的值)。 我看到了“ Worksheet_SelectionChange”方法,但是它不适用于我的示例,因为我们必须打开文件代码并将函数放入其中,并且我想在创建文件时直接执行它。 这是我的例子

sub test(name as string)
  sheet.add

  ActiveSheet.name=name
  i=2

  while i < 10 
    cells(i,1)=i
    i=i+i
  Wend
end sub

1 个答案:

答案 0 :(得分:1)

Worksheet_SelectionChange事件不一定必须驻留在特定于工作表的模块中。例如,它也可以驻留在class module中,并且对于此实例来说很重要的是ThisWorkbook模块(尽管它被命名为Workbook_SheetSelectionChange事件)。

如果您始终希望触发Workbook_SheetSelectionChange事件,而无论 选择在哪个工作表中进行了更改,请尝试以下操作

'place in the ThisWorkbook module
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)

'Do stuff

MsgBox "Changes were made in worksheet: " & Sh.Name, vbInformation

End Sub

如果您只想在最新制作的WS上触发事件

1)您可以确保最新制作的WS始终是WB中的最后一个

'In a regular module
Sub addnwsheet()
Dim shtname As String

With ThisWorkbook

shtname = "temp" & .Sheets.Count
'add a sheet at the end
.Sheets.Add(after:=.Sheets(.Sheets.Count)).Name = shtname

End With

End Sub

'place in the ThisWorkbook module
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)

If Sh.Index = ThisWorkbook.Sheets.Count Then
    'Do stuff

    MsgBox "Selection changed in worksheet: " & Sh.Name, vbInformation
End If

End Sub

2)一种更安全的方法是将新制作的图纸声明为Global变量。这些是持久且公开的。

'In a regular module
Global nwsht As Sheet

Sub addnwsheet()
Dim shtname As String

With ThisWorkbook

    shtname = "temp" & .Sheets.Count
    'add a sheet at the end
    .Sheets.Add(after:=.Sheets(.Sheets.Count)).Name = shtname
    Set nwsht = .Sheets(shtname)

End With

End Sub

'place in the ThisWorkbook module
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)

If Sh = nwsht Then
    'Do stuff

    MsgBox "Selection changed in worksheet: " & Sh.Name, vbInformation
End If

End Sub

编辑

如果您要指定事件触发的范围

'place in the ThisWorkbook module
    Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    Dim r as Range
    Set r = Workbooks(REF).Sheets(REF).Range("D2:D100") 'event will only get triggered by this range

    If Not Intersect(Target, r) Is Nothing Then
        'Do stuff

        MsgBox "Selection changed in worksheet: " & Sh.Name, vbInformation
    End If

    End Sub