我正在尝试在两个工作簿之间进行匹配搜索,以查看在Wbook1中输入的名称是否在Wbook2的A列中。例如......我在工作簿1的单元格D4中有“name1”...然后我希望宏搜索工作簿2的列A以找到“name1”的位置。我并不担心工作簿2上不存在的名称,因为它应该始终存在。
使用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,我会收到'对象或应用程序定义的错误'。代码代表,我得到'无法获取工作表函数类的匹配属性'错误,我不知道为什么。
非常感谢任何帮助。谢谢!
答案 0 :(得分:2)
试试这个。我已对代码进行了评论,因此您无需理解它。
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