我有以下代码让数据在我的工作表中填写(" test")。 r是数字表示将在该表中添加多少组/行数据。 但是,当我打电话给模块时,我第二次引用" r"。它加起来。 如何从同一组/行中获取数据以在工作表的同一行中输入?
Sub addVal(Ctrl As String, Col As Single, tRow As Single)
Dim ii As Single
ii = Me.packageNum.Value - 1 'my control name start from 0 to 9(max)
For i = 0 To ii
Worksheets("test").Cells(tRow, Col).Value = Application.WorksheetFunction.Trim(StrConv(Me.controls(Ctrl & i).Text, vbProperCase))
tRow = tRow+ 1
Next
End Sub
Private Sub Confirm_Click()
Dim r As Single
Call addVal("lot", 4, fEmpty("test")) 'the fEmpty is another module to get the first empty row. working fine
r = 2 ' that was a variable number that get from another userform. now I just change to 2 for testing
Call addVal("estate", 8, r) 'r = 2
Call addVal("stage", 9, r) 'r = 4 (+2)
Call addVal("address", 5, r) 'r = 6 (+2 again)
Call addVal("suburb", 6, r) ' and so on
....... ' calling more same module
End Sub
答案 0 :(得分:1)
在addVal
中,您可以增加第三个参数tRow
。由于您将r
作为该参数传递,因此会增加。如果您只想传递r
的值,而不是传递变量本身,请使用ByVal
:
Sub addVal(Ctrl As String, Col As Single, ByVal tRow As Single)
否则,tRow
函数中的addVal
引用r
中与Confirm_Click
相同的内存位置,更改其中一个会改变另一个。
如果要确保传递对变量的引用而不仅仅是值,请使用ByRef
。这是一个例子:
Sub test()
Dim x As Long, y As Long, z As Long
x = 1
y = 1
z = 1
MsgBox "x = " & x & "; y = " & y & "; z = " & z
Call incrementValues(x, y, z)
MsgBox "x = " & x & "; y = " & y & "; z = " & z
End Sub
Sub incrementValues(ByRef a As Long, ByVal b As Long, c As Long)
a = a + 1
b = b + 1
c = c + 1
MsgBox "a = " & a & "; b = " & b & "; c = " & c
End Sub
最后一个参数是查看默认行为。
如果你谷歌ByVal和ByRef,你会发现更多。