在VBA中创建计数器 [英] Creating a counter in VBA
问题描述
我想知道是否存在使用 Worksheet_SelectionChange
事件在vba上创建计数机制的有效方法?我想计算一个特定单元格被选中的次数.如果选择了该单元格,则变量将增加1,否则将不对变量进行任何更改.
I wanted to know if there is an effective way to create a counting mechanism on vba using a Worksheet_SelectionChange
event?
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.
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
推荐答案
这应该对您有用.将此代码放在要跟踪的工作表的模块后面的代码中.适当更改地址字符串.请注意,这是一种笨拙的表示法,因此 A1
不起作用,但是 $ A $ 1
可以起作用.
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 A1
doesn't work, but $A$1
does.
Option Explicit
Private count As Long
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Debug.Print Target.Address
If Target.Address = "$A$1" Then
count = count + 1
MsgBox count
End If
End Sub
还请注意,您必须在模块级别声明 count
,这样它才不会超出范围并被重置.
Also note that you have to declare count
at the module level so that it doesn't go out of scope and get reset.
这篇关于在VBA中创建计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!