尽管源中包含搜索值,但VBA匹配功能不匹配

时间:2018-08-08 13:07:48

标签: excel vba

Option Explicit

Sub ExtractDivFromAastocks()

    Dim StockCode As String, Anchor As String
    Dim ws As Worksheet

    StockCode = "02800"
    Anchor = "Announce Date"
    Set ws = ExtractRawDivFromAastocks(StockCode)
    Call CleanAastocksDiv(StockCode, ws)

End Sub

Private Function ExtractRawDivFromAastocks(StockCode As String)

    Dim WsFound As Boolean
    Dim i As Integer
    WsFound = False

    For i = 1 To Sheets.Count():
        If Worksheets(i).Name = StockCode Then
            WsFound = True
        End If
        If WsFound = True Then
            Exit For
        End If
    Next i
    If WsFound = True Then
        Application.DisplayAlerts = False
        Worksheets(StockCode).Delete
        Application.DisplayAlerts = True
    End If

    Dim ws As Worksheet
    Dim qt As QueryTable

    Dim Website As String, Aastock As String

    Aastock = "http://www.aastocks.com/en/stocks/analysis/dividend.aspx?symbol="

    Website = Aastock & StockCode

    Set ws = Sheets.Add(After:=Worksheets(Worksheets.Count()))
    ws.Name = StockCode

    Set qt = ws.QueryTables.Add( _
                Connection:="URL;" & Website, _
                Destination:=ws.Range("A1"))

    With qt
        .RefreshOnFileOpen = True
        .Refresh

    End With

    Set ExtractRawDivFromAastocks = ws

End Function

Private Sub CleanAastocksDiv(StockCode As String, ws As Worksheet)

    Dim StartRow As Integer

    StartRow = Application.Match("Announce Date", ws.Range("A:A"), 0)

    ws.Range("A1:" & _
                ws.Cells(StartRow - 1, ws.Columns.Count()).Address).EntireRow.Delete

End Sub

工作表中确实包含字符串值,我不知道为什么匹配失败。我尝试在工作表本身上使用Match函数,它可以工作。这可能是某种参考问题吗?工作表中的单元格似乎没有奇怪的空格。如果有人可以帮助我,那将非常好:

enter image description here

1 个答案:

答案 0 :(得分:0)

Public Sub TestMe()

    Dim ws As Worksheet: Set ws = Worksheets(1)
    Dim StartRow As Variant

    StartRow = Application.Match("Announce Date", ws.Range("A:A"), 0)

    If IsError(StartRow) Then Exit Sub
    If StartRow < 2 Then Exit Sub

    ws.Range("A1:A" & StartRow - 1).EntireRow.Delete

End Sub

  • StartRow声明为Variant,因为如果Announce Date不存在,它将返回错误;
  • 可以使用IsError(StartRow)进行检查,如果不是,则退出;
  • If StartRow < 2 Exit Sub可以避免StartRow为1时可能出现的错误;