[英]Excel VBA - How to find a value in a column and return the row it is on
I currently use a for loop to look through column A in the HDD database sheet and when it finds the matching search criteria it copies all the information in that row into a designated area. 我目前使用for循环浏览HDD数据库工作表中的A列,当找到匹配的搜索条件时,它将该行中的所有信息复制到指定区域中。
I am trying to use the same for loop to tell me which row the search criteria is found on so i can delete that row from the HDD database sheet. 我试图使用相同的for循环来告诉我搜索条件所在的行,这样我就可以从HDD数据库工作表中删除该行。
Tried a few things but nothing seems to work. 尝试了几件事,但似乎无济于事。
Any help is very welcome on this. 任何帮助都非常欢迎。
Private Sub EditButton_Click()
Dim Userentry As String
Dim i As Long
Dim ws, ws1, ws2 As Worksheet
'Dim found As Range
Dim RowNumber As String
Set ws = Sheets("HDD database")
Set ws1 = Sheets("HDD log")
Set ws2 = Sheets("Sheet3")
Userentry = editTxtbox.Value
'ws1.Range("A36").Value = Userentry
For i = 1 To ws.Range("A" & Rows.Count).End(xlUp).Row
If (ws.Cells(i, 1).Value) = Userentry Then
ws2.Range("A1").Offset(1, 0).Resize(1, 8).Value = _
ws.Cells(i, 1).Resize(1, 8).Value
End If
Next i
addnewHDDtxtbox.Value = ws2.Range("A2")
MakeModeltxtbox.Value = ws2.Range("B2")
SerialNumbertxtbox.Value = ws2.Range("C2")
Sizetxtbox.Value = ws2.Range("D2")
Locationtxtbox.Value = ws2.Range("E2")
Statetxtbox.Value = ws2.Range("F2")
For i = 1 To ws.Range("A" & Rows.Count).End(xlUp).Row
If (ws.Cells(i, 1).Value) = Userentry Then
RowNumber = ws.Cells.Row
End If
Next i
ws1.Range("I3").Value = RowNumber
End Sub
Change: 更改:
RowNumber = ws.Cells.Row
to 至
RowNumber = i
I think this should help. 我认为这应该有所帮助。 Using Range.Find() should speed it up a little.
使用Range.Find()应该可以加快速度。 I can edit this if you want more, just comment.
如果您需要更多信息,我可以对其进行编辑,只需发表评论即可。
'I liked your found :)
Dim found As Range
'Set found equal to the cell containing your string
Set found = ws.Range("A:A").Find(Userentry)
'Show the row of found if you want
'MsgBox found.Row
'Delete found's row
'ws.found.Rows.Delete
'Alternately, set the value of I3 to found's row
ws1.Range("I3").Value = ws.found.row
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.