在 VBA 中创建计数器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26619200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a counter in VBA
提问by adt772
I wanted to know if there is an effective way to create a counting mechanism on vba using a Worksheet_SelectionChangeevent?
I want to count how many times a specific cell is selected. If the cell is selected then the variable will go up by one, otherwise no change is made to the variable.
我想知道是否有一种有效的方法可以使用Worksheet_SelectionChange事件在 vba 上创建计数机制?我想计算特定单元格被选中的次数。如果选择了单元格,则变量将增加 1,否则不会对变量进行更改。
Dim S As String
Dim count As Integer
count = 0
S = "$" & "D" & "$" & ActiveCell.Row
If ActiveCell.Address = S Then
count = count + 1
Else
count = count
End If
采纳答案by RubberDuck
This should work for you. Place this code in the code behind module of the worksheet you want to track. Change the address string appropriately. Note that it is aboslute notation, so A1doesn't work, but $A$1does.
这应该对你有用。将此代码放在要跟踪的工作表的代码隐藏模块中。适当更改地址字符串。请注意,它是绝对符号,所以A1不起作用,但$A$1确实如此。
Option Explicit
Private count As Long
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Debug.Print Target.Address
If Target.Address = "$A" Then
count = count + 1
MsgBox count
End If
End Sub
Also note that you have to declare countat the module level so that it doesn't go out of scope and get reset.
另请注意,您必须count在模块级别进行声明,以免超出范围并被重置。

