我想请教您对我的代码的帮助。我试图从另一个工作簿获取值,并通过VLOOKUP将其放在当前的工作簿中。我想使用对工作簿的引用而不是确切的名称,因为搜索工作簿的名称将更改。这是代码:
Sub Thu_submission_ships()
FileToOpen = Application.GetOpenFilename("Microsoft Excel Files (*.xlsx), *.xlsx", 2, "Open last week's EMEA GA Backlog YYYY-MM-DD submission")
Workbooks.Open Filename:=FileToOpen
Set wb_blog = ActiveWorkbook
Set sht_blog = wb_blog.Sheets("Backlog")
Columns("X:X").NumberFormat = "@"
ActiveSheet.Range("X2:Z" & LastRow_blog).Name = "blog"
wb_blog.Save
FileToOpen = Application.GetOpenFilename("Microsoft Excel Files (*.xlsx), *.xlsx", 1, "Open today's GA ships")
Workbooks.Open Filename:=FileToOpen
Sheets("Ships").Select
LastRow2 = Cells(Rows.Count, 1).End(xlUp).Row
Columns("X:X").Insert Shift:=xlToRight
Range("X2:X" & LastRow2).Formula = "=F2&L2"
Range("X2:X" & LastRow2).Copy: Range("X2:X" & LastRow2).PasteSpecial xlPasteValues
Range("X2").Select
Columns("X:X").NumberFormat = "@"
Range("Y2:Y" & LastRow2).Formula = "=VLOOKUP(X2, sht_blog!blog, 2, False)"
End Sub
非常感谢你的帮助!
答案 0 :(得分:0)
您帖子中的代码有点令人困惑,但请参阅下面的代码以了解概念以及解释说明。
Option Explicit
Sub VlookupExample()
Dim FileToOpen As Variant
'grabs workbook
FileToOpen = Application.GetOpenFilename("Microsoft Excel Files (*.xlsx), *.xlsx", 1, "Open today's GA ships")
Workbooks.Open FileName:=FileToOpen
'FileToOpen now stores the workbook full path name
'strip out only workbook name
Dim FileName As String
FileName = Mid(FileToOpen, InStrRev(FileToOpen, "\") + 1, 255)
'Now use in vlookup (same way you would if entered manually in cell.
Range("Y2").Formula = "=vlookup(X2," & FileName & "!blog,2,False)"
End Sub
答案 1 :(得分:0)
您可以在字符串变量中构建公式:
sFormula = "=VLOOKUP(X2,'[" & sht_blog.parent.name &"]" & sht_blog.name &"'!blog, 2,0)"
然后简单地说:
Range("Y2").Formula = sFormula