【问题标题】:Excel VBA: Unable to get the Match property of the WorksheetFunction classExcel VBA:无法获取 WorksheetFunction 类的 Match 属性
【发布时间】:2013-04-19 18:38:38
【问题描述】:

我正在尝试在两个工作簿之间进行匹配搜索,以查看在 Wbook1 中输入的名称是否在 Wbook2 的 A 列中。例如...我在 workbook1 的单元格 D4 中有“name1”...然后我希望宏搜索 workbook2 的 A 列以查找“name1”的位置。我不担心 workbook2 上不存在的名称,因为它应该始终存在。

使用 Excel 2007,代码为:

Sub ViewData()
    Dim xlo As New Excel.Application
    Dim xlw As New Excel.Workbook
    Dim xlz As String
    Dim result As Double
    Dim SalesExec As String
    SalesExec = Range("d4").Value 'D4 contains the name from workbook1 I want to search for
    xlz = Range("y1").value  'This cell contains the file path for workbook 2
    Set xlw = xlo.Workbooks.Open(xlz) 'Path is correct as the desired workbook does open
    result = Application.WorksheetFunction.Match(SalesExec, xlo.Worksheets("Data").Range("A:A"), 0) 'Data is the sheet in workbook2 containing the list of names
    Range("Q14").value = result
    xlw.Save
    xlw.Close
    Set xlo = Nothing
    Set xlw = Nothing
End Sub

如果我删除 .WorksheetFunction,我会收到“对象或应用程序定义错误”。就代码而言,我收到“无法获取工作表函数类的匹配属性”错误,我不知道为什么。

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 为什么是 VBA 而不是 excel 公式?还有为什么不Vlookup
  • 使用 VBA 因为有一些安全验证规则,我最终会通过 VBA 考虑这些规则。使用 Match 而不是 Vlookup,因为我将返回名称所在的整行。验证规则将存在,因为多人将使用宏来查找员工信息。
  • 我还忘了提到 workbook2 将在共享驱动器中,除非工作簿打开,否则我无法使用 excel 公式运行匹配。我希望在不被查看的情况下打开此工作簿,并且需要 VBA 来执行此操作。

标签: excel vba match


【解决方案1】:

试试这个。我已经对代码进行了注释,因此您理解它不会遇到问题。

Sub ViewData()
    Dim xlo As New Excel.Application
    Dim xlw As New Excel.Workbook
    Dim xlz As String
    Dim result As Double
    Dim LRow As Long
    Dim SalesExec As String

    SalesExec = Range("d4").Value

    xlz = Range("y1").Value

    Set xlw = xlo.Workbooks.Open(xlz)

    With xlw.Worksheets("Sheet1")
        '~~> Find the last row cause Range("A:A") in match will give error
        LRow = .Range("A" & .Rows.Count).End(xlUp).Row
    End With

    xlo.Visible = True

    '~~> Result is double so ensure that whatever you are trying to find is as Double
    '~~> Also It should be xlw.Worksheets("Data") and not xlo.Worksheets("Data")
    result = Application.WorksheetFunction.Match(SalesExec, xlw.Worksheets("Data").Range("A1:A" & LRow), 0)

    Range("Q14").Value = result
    xlw.Save
    xlw.Close
    Set xlo = Nothing
    Set xlw = Nothing
End Sub

【讨论】:

  • 优秀。这行得通。也许错误与没有找到最后一行有关?不管怎样,谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-10-13
  • 2015-06-14
  • 2014-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多