vba 循环遍历多选列表框值以创建和命名工作簿
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15483591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping through Multi-selected Listbox values to create and name workbook
提问by Mike
The listbox is not assigning the selected values to "n". The "n" value is 0 regardless if I select values from the listbox or not. I'm learning, so it could be something simple that I'm missing... suggestions? Thanks!
列表框未将所选值分配给“n”。无论我是否从列表框中选择值,“n”值都是 0。我正在学习,所以我遗漏了一些简单的东西......建议?谢谢!
Private Sub UserForm_Initialize()
With cbomonth
.AddItem "January"
.AddItem "February"
End With
With cboyear
.AddItem "2013"
.AddItem "2014"
End With
With cboteam
.AddItem "Team1"
.AddItem "Team2"
End With
With cbodocument
.AddItem "Task1"
.AddItem "Task2"
End With
With ListBox1
.AddItem "Name"
.AddItem "Name"
End With
cboteam.ListIndex = 0
cboyear.ListIndex = 4
cbomonth.ListIndex = 6
cbodocument.ListIndex = 1
End Sub
Private Sub cmdSubmit_Click()
Dim year As String
Dim month As String
Dim days As Integer
Dim team As String
Dim n as Long
Dim tallboxynames As Variant
Dim tallynewfile As String
Unload Me
year = cboyear.Value
month = cbomonth.Value
team = cboteam.Value
document = cbodocument.Value
TallyPath = "\network path\Tally of orders\Master Template\"
TallyPath1 = "\network path\Tally of orders\" & year & "\"
TallyPath2 = "\network path\Tally of orders\" & year & "\" & month & "\"
TallyTemplate = "Tally_Template_ver1.xls"
If document = "Tally Sheets" Then
For n = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(n) Then
tallynewfile = ListBox1.Selected(n) & ".xls"
Else
MsgBox "No data from listbox"
End If
If Len(Dir(TallyPath1, vbDirectory)) = 0 Then
MkDir TallyPath1
End If
If Len(Dir(TallyPath2, vbDirectory)) = 0 Then
MkDir TallyPath2
FileCopy TallyPath & TallyTemplate, TallyPath2 & tallynewfile
End If
Next n
End If
Exit Sub
End Sub
回答by dee
Move the Unload Me to the end of the procedure:
将卸载我移动到程序的末尾:
Private Sub cmdSubmit_Click()
' code here ...
Unload Me
End Sub
To get the selected item use Value if ListBox1.MultiSelect = 0(fmMultiSelectSingle):
要获取所选项目,请使用 Value if ListBox1.MultiSelect = 0(fmMultiSelectSingle):
Me.ListBox1.Value
If MultiSelect > 0 then use Selected property, example:
如果MultiSelect > 0 则使用 Selected 属性,例如:
Private Function GetSelectedItems() As String
Dim text As String
Dim i As Integer
For i = 0 To Me.ListBox1.ListCount - 1
If Me.ListBox1.Selected(i) Then
text = text & Me.ListBox1.List(i) & vbNewLine
End If
Next i
MsgBox "Selected items are: " & text
GetSelectedItemsText = text
End Function
回答by Kazimierz Jawor
Instead of
代替
Unload Me
try to use
尝试使用
Me.Hide
When you unload
all values on the form are deleted. They are kept if you use Hide
.
当您unload
删除表单上的所有值时。如果您使用Hide
.