VBA运行时错误1004-vlookup有时有效

时间:2018-12-11 12:42:09

标签: excel vba vlookup

下面的代码从excel用户表单获取输入,查找该值并预填充用户表单中的其他字段。

它工作愉快,但是现在今天早上似乎只有DealID的工作的某些值和其余的给出以下错误:

  

运行时错误1004无法获取worksheetfunction类的vlookup属性

当我调试并将鼠标悬停在代码上时,它将提供期望在字段中看到的数据。

任何建议都会很棒。

Private Sub GetDetailsButton_Click()

Dim xRg As Range
Set xRg = Worksheets("Deal List").Range("A:U")
Dim DealID As Long

DealID = Me.DealIDBox.Value

Me.AgentNameBox.Text = Application.WorksheetFunction.VLookup(DealID, xRg, 11, False)
Me.LineManagerNameBox.Text = Application.WorksheetFunction.VLookup(DealID, xRg, 12, False)
Me.CustomerRefBox.Text = Application.WorksheetFunction.VLookup(DealID, xRg, 8, False)
Me.ComplexMarkerBox.Text = Application.WorksheetFunction.VLookup(DealID, xRg, 15, False)
Me.DealTimeStampBox.Text = Format(Application.WorksheetFunction.VLookup(DealID, xRg, 3, False), "dd/mm/yy @ hh:mm:ss")
Me.EpicBox.Text = Application.WorksheetFunction.VLookup(DealID, xRg, 14, False)
Me.StockBox.Text = Application.WorksheetFunction.VLookup(DealID, xRg, 17, False)
Me.QuantityBox.Text = Application.WorksheetFunction.VLookup(DealID, xRg, 18, False)
Me.PriceBox.Text = Application.WorksheetFunction.VLookup(DealID, xRg, 19, False)
Me.GrossBox.Text = Application.WorksheetFunction.VLookup(DealID, xRg, 20, False)
Me.DateOfCallBox.Text = Format(Application.WorksheetFunction.VLookup(DealID, xRg, 4, False), "dd/mm/yy")


End Sub

1 个答案:

答案 0 :(得分:3)

每次访问不同的列时保持查找相同的值的效率真的很低,所以我建议您使用Match来查找所需的行,然后直接访问这些单元格:

Private Sub GetDetailsButton_Click()

    Dim xRg As Range
    Set xRg = Worksheets("Deal List").Range("A:U")
    Dim DealID As Long
    Dim matchPos

    DealID = Me.DealIDBox.Value
    matchPos = Application.Match(DealID, xRg.Columns(1), 0)
    If IsError(matchPos) Then
        matchPos = Application.Match(CStr(DealID), xRg.Columns(1), 0)
        If IsError(matchPos) Then
            MsgBox DealID & " not found"
            Exit Sub
        End If
    End If

    Me.AgentNameBox.Text = xRg.Cells(matchPos, 11).Value
    Me.LineManagerNameBox.Text = xRg.Cells(matchPos, 12).Value
    Me.CustomerRefBox.Text = xRg.Cells(matchPos, 8).Value
    Me.ComplexMarkerBox.Text = xRg.Cells(matchPos, 15).Value
    Me.DealTimeStampBox.Text = Format(xRg.Cells(matchPos, 3).Value, "dd/mm/yy @ hh:mm:ss")
    Me.EpicBox.Text = xRg.Cells(matchPos, 14).Value
    Me.StockBox.Text = xRg.Cells(matchPos, 17).Value
    Me.QuantityBox.Text = xRg.Cells(matchPos, 18).Value
    Me.PriceBox.Text = xRg.Cells(matchPos, 19).Value
    Me.GrossBox.Text = xRg.Cells(matchPos, 20).Value
    Me.DateOfCallBox.Text = Format(xRg.Cells(matchPos, 4).Value, "dd/mm/yy")

End Sub

根据您的错误,我想说您xRg表中的某些ID号以文本形式存储,这就是查找失败的原因,因此,如果需要,我也添加了代码来搜索文本版本。 / p>