Instr返回0 Excel VBA

时间:2015-09-16 17:01:48

标签: excel vba excel-vba

第一个Instr()函数给我一个零,即使子字符串显然在我在Yahoos网站上检查过的字符串中。请帮帮我。

Sub ImportBPlans()
Dim BPlan As String, FullHTML As String, URL1 As String, Cut1 As String,  T1   As String
Dim FO As Integer, LO As Integer

For i = 2 To LastRow

    T1 = WB1.Cells(i, 1).Value



    URL1 = "http://finance.yahoo.com/q/pr?s=" + T1 + "+Profile"
    FullHTML = GetHTML(URL1)
    BPlan = "&nbsp;</th></tr></table><p>"
    x = Len(FullHTML)

    FO = InStr(1, FullHTML, BPlan, vbTextCompare) + Len(BPlan)
    LO = InStr(FO, FullHTML, "<")
    Cut1 = Left(FullHTML, LO)
    Cut1 = Right(Cut1, FO - LO)
    WB5.Cells(i, 1).Value = Cut1

Next i


End Sub

Function GetHTML(URL As String) As String
    Dim HTML As String
    Dim htmlBDY As New HTMLDocument
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", URL, False
        .Send
        htmlBDY.body.innerHTML = .responseText
        GetHTML = htmlBDY.body.outerHTML
    End With
End Function

2 个答案:

答案 0 :(得分:1)

为了让它运行和更新,我必须做的是将FO和LO更改为数据类型,因为位置大于整数变量的最大值。

Sub ImportBPlans()
Dim BPlan As String, FullHTML As String, URL1 As String, Cut1 As String,  T1   As String
Dim FO As Long, LO As Long

For i = 2 To LastRow

    T1 = WB1.Cells(i, 1).Value



    URL1 = "http://finance.yahoo.com/q/pr?s=" + T1 + "+Profile"
    FullHTML = GetHTML(URL1)
    BPlan = "&nbsp;</th></tr></table><p>"
    x = Len(FullHTML)

    FO = InStr(1, FullHTML, BPlan, vbTextCompare) + Len(BPlan)
    LO = InStr(FO, FullHTML, "<")
    Cut1 = Left(FullHTML, LO)
    Cut1 = Right(Cut1, FO - LO)
    WB5.Cells(i, 1).Value = Cut1

Next i


End Sub

答案 1 :(得分:0)

过去我在做你尝试的事情时遇到了麻烦。似乎MSHTML或MSXTML或两者都修改了原始HTML,这使得解析它成为一个冒险&#34;。为了让您的代码能够工作,我修改了您的行:

BPlan = "&nbsp;</th></tr></table><p>"

BPlan = "&nbsp;</th></tr></tbody></table>" & vbCrLf & "<p>"

额外的</tbody>vbCrLf来自哪里?不知道。当我使用浏览器查看原始HTML源代码时,我看不到它们,但它们肯定在FullHTML中。 Bob Dole的BPlan似乎应该有效 - 在Dole BPlan的源HTML上进行浏览器查找成功。如果有人可以解释这一点,并且知道如何使用这些工具可靠地解析HTML,我很乐意学习!