簡體   English   中英

Excel VBA-如何在列中查找值並返回其所在的行

[英]Excel VBA - How to find a value in a column and return the row it is on

我目前使用for循環瀏覽HDD數據庫工作表中的A列,當找到匹配的搜索條件時,它將該行中的所有信息復制到指定區域中。

我試圖使用相同的for循環來告訴我搜索條件所在的行,這樣我就可以從HDD數據庫工作表中刪除該行。

嘗試了幾件事,但似乎無濟於事。

任何幫助都非常歡迎。

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

更改:

RowNumber = ws.Cells.Row

RowNumber = i

我認為這應該有所幫助。 使用Range.Find()應該可以加快速度。 如果您需要更多信息,我可以對其進行編輯,只需發表評論即可。

'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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM