Challenge: MS Excel VBA Programming for the Absolute Beginner
I'm learning VBA using a combination of VBA For Dummies and the above mentioned book. The latter, presents a simple challenge (Challenge 2, Chapter 2) that I'd like to ask some for some feedback about.
The challenge is as follows:
Place a Command Button control on a worksheet and write a program in the Click() event procedure that increments a variable by 5 with ever开发者_如何学Goy click of the mouse. Output the value of this variable in a message box.
I've put together the following the code snippet in response:
Sub CommandButton1_Click()
Dim AddClick As Integer
AddClick = Range("A1").Value
AddClick = AddClick + 5
Range("A1").Value = AddClick
MsgBox AddClick
End Sub
Although the code works, I'm pretty sure there's a way to eliminate the use of 'Range("A1").Value' to base the 'AddClick' variable on. How would I go about doing this?
*Update: Thanks to Cody Gray's suggestion (http://articles.techrepublic.com.com/5100-10878_11-5854605.html), I've revised the code to the following - which now works just fine (edited for further simplication):*
Sub CommandButton1_Click()
Static AddClick As Integer
AddClick = AddClick + 5
MsgBox AddClick
End Sub
Simples. Thanks again Cody.
Both previous samples are wrong I think. The correct version is below:
Sub CommandButton1_Click()
Static AddClick As Integer
AddClick = AddClick + 5
MsgBox AddClick
End Sub
Define the variable at module level.
Doing this will increase the scope of the variable from procedure to the module.
Replace the existing code with this one.
Option Explicit
Dim AddClick As Integer
Sub CommandButton1_Click()
AddClick = 0
AddClick = AddClick + 5
MsgBox (AddClick)
End Sub
Note: Defining the variable at procedure level will limit its life.
i.e. the variable won't be accessible outside the scope of the procedure.
精彩评论