这似乎是一个简单的问题,但我找不到有效的解决方案。 基本上,在我的代码中,现在工作簿已硬编码为其名称。
但是,我希望能够根据用户在特定单元格上输入的内容来更改名称;而不是Workbooks(“ OH Detail v13”),而是Workbooks(“ Sheet FilePath的单元格C2中的所有内容”)
Dim openbook As Workbook
Dim xpath As String, xfile As String, xext As String
xpath = Sheets("FilePath").Range("C2").Value 'This is where there is the workbook name I want to be dynamic
xfile = "\" & Sheets("FilePath").Range("C3").Value
xext = ".xlsx"
Set openbook = Workbooks.Open(xpath & xfile & xext) 'This works
`This is where I want the dynamic Workbook name:
Workbooks("OH Detail v13").Sheets("Invoices").Select
ActiveSheet.PivotTables("Invoices").PivotSelect "", xlDataAndLabel, True
Selection.Copy 'Copied into the workbook where the code is
Workbooks("OH Details_v2").Sheets("Data").Range("A1").PasteSpecial Paste:=xlPasteValues
我尝试添加:
Dim wsOG As Workbook
Set wsOG = Workbooks(xpath)
wsOG.Sheets("Invoices").Select
它给我错误:对象变量或With块变量未设置
答案 0 :(得分:0)
希望这会有所帮助:
XPath = Sheets("FilePath").Range("C2").Value 'This is where there is the workbook name I want to be dynamic
xfile = Sheets("FilePath").Range("C3").Value
xext = ".xlsx"
'Open a workbook
Set wsOG = Workbooks.Open(XPath & "\" & xfile & xext, UpdateLinks:=False, ReadOnly:=True) 'Parameters are optional
'Set a workbook which is already open
Set wsOG = Workbooks(xfile & xext)
请注意,我已经从您的xfile变量中删除了“ \”,因为当您要设置打开的工作簿时,它不起作用。