2016-08-25 57 views
0

我有下面的代碼讓數據填充到我的工作表(「測試」)中。 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

你只在'Confirm_Click()'中使用'r'?從上面的代碼中,我看不到任何'r'變成了'r = 2'的地方。所以你必須在代碼的另一部分添加它,然後再回到下一次調用'addVal()' – DragonSamu

回答

1

addVal,你增加了第三個參數tRow。由於您通過r作爲該參數,它會增加。如果你只是想通過的r值,不是變量本身,使用ByVal

Sub addVal(Ctrl As String, Col As Single, ByVal tRow As Single) 

否則,tRowaddVal功能Confirm_Click引用相同的存儲單元r和改變其中一人將改變另一個。

如果要確保傳遞變量的引用而不僅僅傳遞值,請使用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你會發現更多的。

+0

謝謝,現在它可以工作。我不知道tRow會將增量推回給參考。再次感謝你。 –