繁体   English   中英

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

[英]VBA match function mismatch despite having the search value in source

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函数,它可以工作。 这可能是某种参考问题吗? 工作表中的单元格似乎没有奇怪的空格。 如果有人可以帮助我,那将是非常不错的事情:

在此处输入图片说明

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则需要If StartRow < 2 Exit Sub ,以避免StartRow为1时可能出现的错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM