Using Multiple Variables with the Same Name

ljm0211發表於2012-07-02
   If public variables in different modules share the same name, it's possible to differentiate between them in code by referring to both the module and variable names. For example, if there is a public Integer variable intX declared in both Form1 and in Module1, you can refer to them as Module1.intX and Form1.intX to get the correct values.

To see how this works, insert two standard modules in a new project and draw three command buttons on a form.

One variable, intX, is declared in the first standard module, Module1. The Test procedure sets its value:

Public intX As Integer ' Declare Module1's intX.
Sub Test()
' Set the value for the intX variable in Module1.
intX = 1
End Sub

The second variable, which has the same name, intX, is declared in the second standard module, Module2. Again, a procedure named Test sets its value:

Public intX As Integer ' Declare Module2's intX.
Sub Test()
' Set the value for the intX variable in Module2.
intX = 2
End Sub

The third intX variable is declared in the form. module. And again, a procedure named Test sets its value.

Public intX As Integer ' Declare the form's intX
' variable.
Sub Test()
' Set the value for the intX variable in the form.
intX = 3
End Sub

Each of the three command buttons' Click event procedures calls the appropriate Test procedure and uses MsgBox to display the values of the three variables.

Private Sub Command1_Click()
Module1.Test ' Calls Test in Module1.
MsgBox Module1.intX ' Displays Module1's intX.
End Sub

Private Sub Command2_Click()
Module2.Test ' Calls Test in Module2.
MsgBox Module2.intX ' Displays Module2's intX.
End Sub

Private Sub Command3_Click()
Test ' Calls Test in Form1.
MsgBox intX ' Displays Form1's intX.
End Sub

Run the application and click each of the three command buttons. You'll see the separate references to the three public variables. Notice in the third command button's Click event procedure, you don't need to specify Form1.Test when calling the form's Test procedure, or Form1.intX when calling the value of the form's Integer variable. If there are multiple procedures and variables with the same name, Visual Basic takes the value of the more local variable, which in this case, is the Form1 variable.

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/11411056/viewspace-734287/,如需轉載,請註明出處,否則將追究法律責任。

相關文章