美好的一天 我有一张名为" MACRO"使用预定义的工作簿作为源和目标运行多个宏。
在这个特殊要求中,我想在我的宏表中运行一个宏,它将在" book2.xslx"上使用vlookup。使用查找单元格,在" book3.xlsx"中查找值并更新" book2.xlsx"结果
那里的所有宏都从活动工作表中运行vlookup,但是我找不到任何可以做的事情。
请帮助:)
由于
更确切地说,我正在尝试执行以下操作:
打开" book2.xlsx",转到第34列;" b" "单元格2"并插入以下公式 " = VLOOKUP(A2,[Book3.xlsx] Sheet 1中$ A:$ B,2,0)" 一直使用的相同公式直到"查找单元"变为空白",而#34; A2"中的值每当它移动到下面的单元格时应该改变
你能帮帮忙吗?编辑:代码我试图运行:
Sub VLOOKUP_DEPT()
Dim wbk1 As Workbook
strFirstFile = "C:\Users\hayekn\Desktop\book2.xlsx"
Set wbk1 = Workbooks.Open(strFirstFile)
With wbk1.Sheets("sheet1")
Range("B2") = Application.WorksheetFunction.vlookup(Range("A2"), Workbooks("C:\Users\hayekn\Desktop\book3.xlsx").Sheets("sheet1").Range("A:B"), 2, 0)
End With
wbk1.Close True
MsgBox ("VLOOLUP-DEPT Completed!!")
End Sub
我也尝试了这一点,它贯穿但未返回" book2"
Sub VLOOKUP_DEPT()
Dim wbk1 As Workbook
strFirstFile = "C:\Users\hayekn\Desktop\book2.xlsx"
strSecondFile = "C:\Users\hayekn\Desktop\book3.xlsx"
Set wbk1 = Workbooks.Open(strFirstFile)
Set wbk2 = Workbooks.Open(strSecondFile)
Set Rng = wbk1.Sheets("Sheet1").Range("B2")
Set Rng2 = wbk1.Sheets("Sheet1").Range("A2")
Set Rng3 = wbk2.Sheets("sheet1").Range("A:B")
Rng = Application.vlookup(Rng2, Rng3, 2, 0)
wbk1.Close True
wbk2.Close True
MsgBox ("VLOOLUP-DEPT Completed!!")
End Sub
由于
答案 0 :(得分:1)
不幸的是,VBA VLookup并不适用于已关闭的工作簿。但细胞配方确实如此。
另外值得注意的是
Sub的重构版本,用于处理已关闭的工作簿
Sub VLOOKUP_DEPT()
Dim strFirstFile As String
Dim strLookup As String
Dim wbk1 As Workbook
Dim wbkLookup As Workbook
Dim clLookup As Range
Dim clDest As Range
strFirstFile = "C:\Users\hayekn\Desktop\book2.xlsx"
Set wbk1 = Workbooks.Open(strFirstFile)
strLookup = "'C:\Users\hayekn\Desktop\[book3.xlsx]Sheet1'!A:B"
With wbk1.Sheets("sheet1")
Set clDest = .Range("B2")
Set clLookup = .Range("A2")
End With
clDest.Formula = "=VLOOKUP(" & clLookup.Address & "," & strLookup & ",2,0)"
clDest.Value = clDest.Value ' Convert to value
wbk1.Close True
MsgBox ("VLOOLUP-DEPT Completed!!")
End Sub
修改版本以填充Lookup列中所有已使用的行
Sub VLOOKUP_DEPT()
Dim strFirstFile As String
Dim strLookup As String
Dim wbk1 As Workbook
Dim wbkLookup As Workbook
Dim clLookup As Range
Dim clDest As Range
Dim rws As Long
strFirstFile = "C:\Users\hayekn\Desktop\book2.xlsx"
Set wbk1 = Workbooks.Open(strFirstFile)
strLookup = "'C:\Users\hayekn\Desktop\[book3.xlsx]Sheet1'!A:B"
With wbk1.Sheets("sheet3")
Set clDest = .Range("B2")
Set clLookup = .Range("A2")
End With
If clLookup.Offset(1, 0) <> vbNullString Then
rws = Range(clLookup, clLookup.End(xlDown)).Rows.Count
Set clDest = clDest.Resize(rws, 1)
End If
clDest.Formula = "=VLOOKUP(" & clLookup.Address(False, False) & "," & strLookup & ",2,0)"
clDest.Value = clDest.Value ' Convert to value
wbk1.Close True
MsgBox ("VLOOLUP-DEPT Completed!!")
End Sub