错误424:在循环中使用Vlookup所需的对象

时间:2016-09-26 20:14:44

标签: excel vba excel-vba excel-formula vlookup

基本上我在这里尝试做的是让我的宏构建一个URL,它将被抓取并用于填充信息。我打算根据指定的特定证券和数据字段使URL唯一。

我在j循环中使用vlookup中的数据类型字符串收到错误。我打算让它返回一个用于填充我的URL的值。

Dim Last1 As Integer: Last1 = W.Range("A1000").End(xlUp).Row
Dim Last2 As Integer: Last2 = W.Range("XFD1").End(xlToLeft).Column
Dim IE As SHDocVw.InternetExplorer
Dim html As HTMLDocument
If Last = 1 Then Exit Sub
Dim Symbols As String
Dim DataType As String
Dim URLParameters As String
Dim i, j As Integer


    For i = 2 To Last1
        Symbols = Symbols & Worksheets("Stock Prices").Range("A" & i).Value & "+"
    Next i

    Symbols = Left(Symbols, Len(Symbols) - 1)

    Debug.Print Symbols

    For j = 2 To Last2

        DataType = DataType & Worksheets("Stock Prices").Cells(1, j).Value

        URLParameters = Application.WorksheetFunction.VLookup(DataType, Worksheets("URL Info").Range("URL_DataInfo"), 2).Value

    Next j
    Debug.Print DataType
    Debug.Print URLParameters

Set IE = CreateObject("InternetExplorer.Application")

'Tells IE where to pull
IE.navigate "https://download.finance.yahoo.com/d/quotes?s=" & Symbols & "&f=" & URLParameters
IE.Visible = True

'Wait until IE is done loading page
Do While IE.readyState <> READYSTATE_COMPLETE
Application.StatusBar = "Pulling data..."
DoEvents
Loop
'show text of HTML document returned
Set html = IE.document
'MsgBox html.DocumentElement.innerHTML
'close down IE and reset status bar
Set IE = Nothing
Application.StatusBar = ""

'Remove HTML tags
Dim info As String
info = cook_tags(CStr(html.DocumentElement.innerHTML))

'Split the results into cells
Call split_data(info)

End Sub

2 个答案:

答案 0 :(得分:2)

您当前的代码要求VLOOKUP function进行相应的匹配。数据必须按升序排序,以便远程工作。

使用variant-type接受返回的值并删除WorksheetFunction object。如果仅使用Excel Application object,则可以将错误返回给变体。

您没有返回Range.Value property,只是返回VLOOKUP的值。

Dim URLParameters As variant
URLParameters = Application.VLookup(DataType, Worksheets("URL Info").Range("URL_DataInfo"), 2, FALSE)
if IsError(URLParameters) Then
    'no value found
else
    'value found and put in URLParameters
end if

答案 1 :(得分:0)

VLOOKUP公式从匹配的单元格返回。尝试

URLParameters = Application.WorksheetFunction.VLookup(DataType, Worksheets("URL Info").Range("URL_DataInfo"), 2)

代替这一点(注意函数调用结束时的.Value,这是不正确的):

URLParameters = Application.WorksheetFunction.VLookup(DataType, Worksheets("URL Info").Range("URL_DataInfo"), 2).Value

如果Vlookup函数的返回数据类型不是字符串(即,特别是如果它是错误类型),则可能会收到更多错误。在这种情况下,最好测试错误,并避免使用WorksheetFunction类:

With Worksheets("URL Parameters")
    If Not IsError(Application.VLookup(DataType, .Range("URL_DataInfo"), 2)) Then
        URLParameters = Application.VLookup(DataType, .Range("URL_DataInfo"), 2)
    Else

        '## Here, you'll need some error handling or exit sub early, etc.

    End If
End With