我有一个模板,用其他工作簿中的销售数据填充某些单元格,但另一个工作簿每个月都有一个新名称。当我尝试将变量指定为工作簿名称以便每次都找到它时,我无法使索引/匹配函数起作用。不确定错误的位置,但是VBA脚本失败的地方......
Sub GetNetSales()
Dim Period As String
Dim NS As Workbook
Dim Can As Workbook
Dim BookName As String
Period = Range("Per").Value
Set Can = ThisWorkbook
ChDir "C:\Users\dlibby\Documents\" & Period
Workbooks.Open Filename:= _
"C:\Users\dlibby\Documents\" & Period & "\Net Sales " & Period & ".xlsx"
Set NS = ThisWorkbook
Can.Activate
Range("C10").Select
ActiveCell = _
Application.IfError(Application.Index(NS.Sheets("CM Sales").Columns("E:E"), Application.Match(Can.Range("H10").Value, NS.Sheets("CM Sales").Columns("A:A"), 0)), 0).Value
Range("C10").Select
Selection.Copy
Range("C11:C12").Select
ActiveSheet.Paste
Range("C16:C22").Select
ActiveSheet.Paste
Application.Calculate
Range("C10:C12").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("C16:C22").Select
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
答案 0 :(得分:0)
当我在宏中使用索引/匹配时,我输入的公式如下:
Folder = Sheets("Overview").Range("F4")
filename = Sheets("Overview").Range("G4")
filetype = Sheets("Overview").Range("H4")
tabname = Sheets("Overview").Range("I4")
style = Sheets("Overview").Range("J4")
SAPsizecode = Sheets("Overview").Range("K4")
ActiveCell.Formula = "=INDEX('" & Folder & "\[" & filename & filetype & "]" & tabname & "'!$" & SAPsizecode & ":$" & SAPsizecode & ",MATCH(C2,'" & Folder & "\[" & filename & filetype & "]" & tabname & "'!$" & style & ":$" & style & ",0))"
这对我有用。我认为代码中的问题是如何分配工作簿。使用上述方法,您无需打开另一个工作簿。