Dim InputCol, InputIndex, i As Long
Dim lb As ListBox
InputCol = 1
For i = 1 To 7
Set lb = Me.Controls("ListBox" & i)
For InputIndex = 0 To lb.ListCount - 1
If lb.Selected(InputIndex) Then
Sheets("Sheets2").Cells(1, InputCol) = Sheets("Sheet1").Range("Input" & i).Cells(InputIndex)
InputCol = InputCol + 1
End If
Next
Next i我试图使用上面的代码循环一个用户表单中的多个列表框。列表框从Sheet1上的命名范围派生数据,然后将标题传递给Sheet2。Sheet1范围与列表框按编号对齐。不幸的是,我收到了一个运行时错误“13”:引用行的类型错配:
Set lb = Me.Controls("ListBox" & i)有什么想法吗?
发布于 2017-06-30 03:25:08
非常感谢Shai Rado为我指明了正确的方向。以下代码用于遍历用户窗体上的所有列表框,并将每个选定项传递给Sheet2上的标题行:
Private Sub CommandButton1_Click()
Dim InputCol As Long, InputIndex As Long, i As Long
Dim lb As Control
InputCol = 1
With lb
For i = 1 To 7
Set lb = Me.Controls("ListBox" & i)
For InputIndex = 0 To lb.ListCount - 1
If lb.Selected(InputIndex) Then
Sheets("Sheet2").Cells(1, InputCol) = _
Sheets("Sheet1").Range("Input" & i).Cells(InputIndex + 1)
InputCol = InputCol + 1
End If
Next
Next i
End With
Unload Me
End Sub发布于 2017-06-29 05:35:22
使用下面的代码循环遍历UserForm中的所有UserForm,并检查当前控件是否为ListBox。
Note:Dim InputCol, InputIndex, i As Long,意味着只有i被定义为Long,而InputCol和InputIndex被定义为As Variant。
码
Dim InputCol As Long, InputIndex As Long, i As Long
Dim lb As Control
InputCol = 1
' loop through all control in UserForm
For Each lb In Me.Controls
' check if current Control is a LitBox
If TypeName(lb) = "ListBox" Then
With lb
' rest of your code goes here
End With
End If
Next lbhttps://stackoverflow.com/questions/44816899
复制相似问题