试着看了这个,但我还是VBA的新手并且仍然很困惑。我无法弄清楚如何从一个sub获取变量并在另一个sub中使用它。
我想从ListBox1Items
获取变量GetListBox1Items
并在cbSave_Click
中使用它。我一直在Set oNewRow = Selection.ListObject.ListRows.Add(1)
收到错误。我尝试了Dim ListBox1Items As String
和Public 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 :(得分: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
在UserForm代码中:
Private Sub cbSave_Click()
Call GetListBoxItems
Debug.Print ListBoxItems
End Sub