我想在Sheet1的B列中找到具有匹配值的单元格(或行),并将其放入ListBox2中。然后,我想将单元格的值更改为4列(使用Offset命令)。
我相信使用For循环是遍历ListBox2中的值的最有效方法。我尝试使用Forloop遍历放置在ListBox2.List中的所有值。调用一个值后,代码将在B列中查找该值。找到后,它将“记住”在其中找到该值的行。然后,代码将使用“范围/偏移”命令来更改该行中4列以上的单元格的值。
Private Sub ButtonOK_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim SerialList As Range
Dim SerialRow As Long
Dim i As Long
Set wb = ActiveWorkbook
Set ws = ActiveWorkbook.Worksheets("Sheet1")
Dim strFind As Variant
With ws
For i = 0 To Me.ListBox2.ListCount - 1
Set SerialList = ws.Range("B:B").Find(What:=Me.ListBox2.List(i))
SerialRow = SerialList.Row
If Not SerialList Is Nothing Then
ws.Range("B", SerialRow).Offset(0, 4).Value = Me.ListBox2.List(i) 'error occurs here!
MsgBox (ListBox2.List(i) & " found in row: " & SerialList.Row)
Else
MsgBox (ListBox2.List(i) & " not found")
End If
Next i
End With
End Sub
MsgBoxes确实说出正确的ListBox2.List(i)值和正确的SerialList.Row,这意味着程序正在正确地找到列表框值所在的行。但是,我收到一条错误消息,提示我的范围未在“ ws.Range(“ B”,SerialRow).....“行中正确定义。
如何选择要搜索的单元格以将其正确设置为= Me.ListBox2.List(i)?
答案 0 :(得分:1)
修复程序组合:
Dim lv
'....
For i = 0 To Me.ListBox2.ListCount - 1
lv = Me.ListBox2.List(i)
Set SerialList = ws.Range("B:B").Find(What:=lv, LookAt:=xlWhole) '<< be more explicit
'don't try to access SerialList.Row before checking you found a match...
If Not SerialList Is Nothing Then
ws.Cells(SerialList.Row, "F").Value = lv '<< Cells in place of Range
MsgBox (lv & " found in row: " & SerialList.Row)
Else
MsgBox (lv & " not found")
End If
Next i