如何获取Excel中单词的第二个(或最后一个)出现的行号?

时间:2018-05-09 13:41:45

标签: vba excel-vba excel

我正在从Excel工作表的网页中复制一些内容,然后搜索特定的单词,然后获取记录的行号。复制的内容来自HTML页面,并以excel格式的表格格式粘贴。有时,表中会提到两次这个词,我想得到最后一个记录的行号。我有第一次获取行号的代码,但我无法弄清楚最后一条记录的行号。当我获取行号值时,在变量" row_no"中,我需要在最后显示的记录的行号。我怎么能得到它? 请在下面找到我写的代码:

Set ie = New InternetExplorerMedium
            ie.Visible = True
            ws.Activate
strHTML = URL
            ie.navigate strHTML
Do While ie.Busy Or ie.READYSTATE <> 4
                DoEvents
            Loop

            Set oXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP")
            Set objCollection = ie.document.getElementsByTagName("input")

            Set tables = ie.document.getElementsByTagName("Table")

            msg = ie.document.Body.innerHTML

              If InStr(msg, "Word1") = 0 Then
            Else
               For x = 0 To tables.Length

                        If tables(x).innerText Like "*Word1*" Then
                         found = True

                         If x > 0 Then
                         Set clipboard = New MSForms.DataObject
                         clipboard.SetText tables(x).outerHTML
                         clipboard.PutInClipboard
                         ws.Activate
                         ws.Range("A1").PasteSpecial
                         Result = Application.WorksheetFunction.CountIf(Range("E2:E10000"), "End Analysis")
                         MsgBox Result
                         If Result> 1 Then
'get the row number                            
                          row_no = Worksheets("temp").Range("E2:E10000").Find("End Analysis", lookat:=xlWhole).Row
                         End If
                         End If
                    Next x
                 End If   

1 个答案:

答案 0 :(得分:0)

喜欢这个

Option Explicit

Public Sub test()
    Dim found As Range
    With Worksheets("temp").Range("E2:E10000")
       Set found = .Find(what:="End Analysis", searchorder:=xlByColumns, searchdirection:=xlPrevious)
       If Not found Is Nothing Then Debug.Print found.Row
    End With
End Sub

看起来像你的更多:

Dim found As Range, row_no As Long
If Result > 1 Then
   Set found = Worksheets("temp").Range("E2:E10000").Find(what:="End Analysis", searchorder:=xlByColumns, searchdirection:=xlPrevious)
   If Not found Is Nothing Then 
       row_no = found.Row
   Else
      MsgBox "Not Found"
   End If
End If