我目前正在尝试根据ListBox中选择的内容更改某个单元格值。
这就是我构建列表框的方式
Private Sub cmdAdd2_Click()
Dim LR As Long
Dim r As Long
Dim i As Long
lstSelector.Clear
With ActiveSheet
LR = .Range("A" & .Rows.Count).End(xlUp).Row
For r = 2 To LR
If .Cells(r, 1).Value = Val(TextBox6.Value) And .Cells(r, 5).Value = "No" Then
lstSelector.AddItem .Cells(r, 2).Value
lstSelector.List(i, 1) = .Cells(r, 3).Value
i = i + 1
End If
Next r
End With
这是我的意图。我遇到的问题是如何选择和编辑第5列单元格。
Private Sub cmdAdd_Click()
Range("Trades").Cells(Me.lstSelector.ListIndex + 2, 5) = "Yes"
上面的代码有效,但只是温和,并在刷新列表框时编辑“随机”行。我猜测这部分代码存在问题。
我想要发生的是Cell32中选择的行的Cell#5,当点击cmdAdd_Click()时将其值更改为“是”。
答案 0 :(得分:0)
在你的第二段代码(Range("Trades").Cells(Me.lstSelector.ListIndex + 2, 5) = "Yes"
)中,你正在选择ListIndex,它指向列表中项目的位置(第一,第二,第三......),这与行是数据在您的工作表中。
试试这个:
Private Sub cmdAdd2_Click()
Dim LR As Long
Dim r As Long
Dim i As Long
lstSelector.Clear
With ActiveSheet
LR = .Range("A" & .Rows.Count).End(xlUp).Row
For r = 2 To LR
If .Cells(r, 1).Value = Val(TextBox6.Value) And .Cells(r, 5).Value = "No" Then
lstSelector.AddItem .Cells(r, 2).Value
lstSelector.List(i, 1) = .Cells(r, 3).Value
lstSelector.List(i, 2) = .Cells(r, 3).Row 'this line added for storing row number
i = i + 1
End If
Next r
End With
End Sub
然后
Private Sub cmdAdd_Click()
Dim lItem As Long
For lItem = 0 To lstSelector.ListCount - 1 'Scan all items in lstSelector
If lstSelector.Selected(lItem) = True Then 'if selected...
Worksheets("Trades").Cells(lstSelector.List(lItem, 2), 5) = "Yes" 'recall row number
End If
Next
End Sub