,您好。我是VBA新手
我有一个包含多列数据的listbox1。每次我点击删除按钮,我都希望它填充.cell(第8行),它位于状态栏下,#34;丢弃"对于每个数据。我已完成以下代码。我可以多选我的行但是在选定的行中,只有一行可以更改其状态。请帮忙。谢谢。
Private Sub DeleteCartonButton_Click()
Dim cl As Range
Dim rIds As Range
Dim Rw As Long
Dim String1 As String
Dim i As Long, msg As String, Check As String
'Generate a list of the selected items
With ListBox1
For i = 0 To .ListCount - 1
If .Selected(i) Then
msg = msg & .List(i) & vbNewLine
String1 = Menu.ListBox1.List(Menu.ListBox1.ListIndex, 0)
With Sheet1
Set rIds = .Range(.Cells(2, 1), .Cells(.Rows.Count, 1).End(xlUp))
With rIds
Set cl = .Find(String1, LookIn:=xlValues)
If Not cl Is Nothing Then Rw = cl.Row
End With
.Cells(Rw, 8).Value = "Discarded"
End With
UserForm_Initialize
End If
Next i
End With
If msg = vbNullString Then
'If nothing was selected, tell user and let them try again
MsgBox "No Carton was selected. Please make a selection."
Exit Sub
End If
End Sub
答案 0 :(得分:2)
根据您的评论,试试这个:
'~~> get all the selected indexes
Dim myindex, index
With ListBox1
For i = 0 To .ListCount - 1
If .Selected(i) Then
If Not IsArray(myindex) Then
myindex = Array(i)
Else
ReDim Preserve myindex(UBound(myindex) + 1)
myindex(UBound(myindex)) = i
End If
End If
Next
End With
If IsEmpty(myindex) Then Exit Sub '~~> if nothing is selected
'~~> update the sheet
With Sheet1
For Each index In myindex
.Range("H2").Offset(index,0).Value = "Discarded"
Next
End With
'~~> update the ListBox1 display
DoEvents
Listbox1.RowSource = "'[WorkbookName]SheetName'!RangeAddress"
您需要DoEvents
直观地更新 ListBox
我还指出你应该明确指定 RowSource属性
这样可以避免错误和意外输出
我假设您的数据在Cell H2中开始,否则将替换它。