首页 > 解决方案 > 运行时错误 1004 无法使用 url 链接名称查找列

问题描述

我正在尝试借助 Microsoft XLS 中的 VBA 搜索该列。

这是我的 xlsx 数据

---------------------------------------------------------------------
|Column1 |Column2 |Column3 |Column4 |Column5 |Column6                |
---------------------------------------------------------------------
|Dataxxx |Olivier |  40    | 100    |  1163  | https://www.facebook.com/groups/xxx/permalink/1338777099605419/      |
----------------------------------------------------------------------
|Dataxxx |Geovanny| 35     | 101    |  1147  |  https://www.facebook.com/groups/xxx/permalink/1338288259654303/      |
----------------------------------------------------------------------
|Dataxxx |Julien  | 33     |  66    |  1200  | https://www.facebook.com/groups/xxx/permalink/1339487882867674/      |
----------------------------------------------------------------------

这是我尝试过的代码:

Sub myMacro()

    Dim myLookupValue As String
    Dim myFirstColumn As Long
    Dim myLastColumn As Long
    Dim myColumnIndex As Long
    Dim myFirstRow As Long
    Dim myLastRow As Long
    Dim myVLookupResult As String

    Dim myTableArray As Range

    myLookupValue = "https://www.facebook.com/groups/xxx/permalink/1338777099605419/"
    myFirstColumn = 2
    myLastColumn = 6
    myColumnIndex = 5
    myFirstRow = 2
    myLastRow = 4

    With Worksheets("Sheet1")
        Set myTableArray = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn))
    End With

    myVLookupResult = WorksheetFunction.VLookup(myLookupValue, myTableArray, myColumnIndex, False)

    MsgBox "My lookup value " & myLookupValue & " are "

End Sub

我该如何解决这个问题?

标签: excelvba

解决方案


编辑:您的查找表在错误的列中有查找值。VLOOKUP要求查找值存在于查找表的第一列中,但您正在查找 url,它是数据中的最后一列。

工作原理VLOOKUP是给它一个查找值(例如“dataxxxx”),告诉它要在哪里找到该值(例如,那里的单元格范围 - 查找值总是在最左边的列中),然后从左侧的哪一列中提取查找结果:如果要获取URL,则该 URL 不能是您的查找值

原始答案如下。


myColumnIndex无法匹配myLastColumn;您正在查找表之外的一列,该表从B( myFirstColumn = 2) 列开始。

myColumnIndex = myLastColumn - myFirstColumn + 1

应该修复它。

请注意,如果查找失败(即#N/A在工作表上返回),WorksheetFunction.VLookup则会引发您需要处理的运行时错误。

如果查找失败不是异常情况,请考虑使用后期绑定Application.VLookup等效项,它将返回错误:

Dim myVLookupResult As Variant ' <~ note the return type
myVLookupResult = Application.VLookup(myLookupValue, myTableArray, myColumnIndex, False)

If IsError(myVLookupResult) Then
     'vlookup returned #N/A 'string coercion would throw a type mismatch here
Else
     MsgBox myVLookupResult 'string coercion is safe/valid here
End If

推荐阅读