Creating a counter in VBA

眉间皱痕 提交于 2021-01-28 00:15:00

问题


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

回答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

Also note that you have to declare count at the module level so that it doesn't go out of scope and get reset.



来源:https://stackoverflow.com/questions/26619200/creating-a-counter-in-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!