2017-11-10 29 views
0

試圖查看這個,但我仍然是VBA的新手,仍然很困惑。我無法弄清楚如何從一個子變量中獲取變量並在另一個子變量中使用它。如何從模塊中的子變量中使用變量,並在用戶窗體的另一個子功能中使用Excel VBA

我想從GetListBox1Items獲取變量ListBox1Items並在cbSave_Click中使用它。我一直收到Set oNewRow = Selection.ListObject.ListRows.Add(1)的錯誤。我試過Dim ListBox1Items As StringPublic ListBox1Items As String但這沒有幫助。

是否子模塊的位置? GetListBox1Items在模塊中。 cbSave_Click位於UserForm中。

我擡頭看着使用類型,但它變得混亂。

Private Sub cbSave_Click() 
Dim oNewRow As ListRow 
Dim rng As Range 
Set rng = ThisWorkbook.Worksheets("Creatures").Range("MonsterList") 
Set oNewRow = Selection.ListObject.ListRows.Add(1) 


With ws 

Call GetListBox1 

oNewRow.Range.Cells(1, 24).Value = Me.StatBox1.Value 
oNewRow.Range.Cells(1, 35).Value = ListBox1Items 

End With 
End Sub 

和GetListBox1是

Sub GetListBox1() 
Dim SelectedItems As String 
Dim ListBox1Items As String 


With MonsterMaker 
    For i = 0 To .ListBox1.ListCount - 1 
     If .ListBox1.Selected(i) = True Then 
      SelectedItems = SelectedItems & .ListBox1.List(i) & ", " 
     End If 
    Next i 

    ListBox1Items = Left(SelectedItems, Len(SelectedItems) - 2) 


End With 
End Sub 
+0

您需要將其設爲全局變量。一些指針https://stackoverflow.com/questions/2722146/how-do-i-declare-a-global-variable-in-vba – QHarr

+0

你可以讓GetListBox1函數返回ListBox1Items的值 – mooseman

+0

嘗試設置全局變量在用戶窗體和模塊中,但仍然出現'Set oNewRow = Selection.ListObject.ListRows.Add(1)'錯誤。 – bigbucky

回答

0

採取按照抽象的例子:

標準模塊的代碼:

Option Explicit 
Public ListBoxItems As String 'GLOBAL 

Sub GetListBoxItems() 

    Dim selectedItems As String 
    Dim i as long 

    With ThisWorkBook.Worksheets("Sheet1").OLEObjects("ListBox1").Object 'amend as appropriate 
     For i = 0 to .ListCount-1 
      If .Selected(i) Then 
       selectedItems = selectedItems & .List(i) & ", " 
      End If 
     Next i 
     ListBoxItems = Left$(selectedItems,Len(selectedItems)-2) 
    End With 

End Sub 

在用戶窗體代碼:

Private Sub cbSave_Click() 
    Call GetListBoxItems 
    Debug.Print ListBoxItems 
End Sub 
+0

無法正常工作。仍然收到錯誤'Set oNewRow = Selection.ListObject.ListRows.Add(1)' – bigbucky

+0

$ left之後會做什麼?我無法找到記錄。 – bigbucky

+0

這個例子是一個抽象的例子,向你展示如何傳遞變量?例如,我不知道MonsterMaker是什麼。並且以下語法是否正確? Selection.ListObject.ListRows.Add(1) – QHarr

相關問題