我正在尝试在Excel中运行一个宏,用户选择要打开的文件,宏将从该工作簿中复制一个范围并将其粘贴到原始工作簿中的用户指定单元格。我对代码的尝试如下所示。我将“wbThis”作为要粘贴的原始工作簿和“wbTarget”作为正在打开和复制的工作簿。当我运行代码时,我可以选择要打开的文件,但是它会出现“需要对象”的错误,并且不会进一步复制和粘贴。
有没有办法使用Workbook.Open而不是Application.GetOpenFilename,但仍然可以让用户选择要打开的文件?
感谢您的帮助。
Dim wbTarget As Workbook
Dim wbThis As Workbook
Set wbThis = ActiveWorkbook
Set wbTarget = Application.GetOpenFilename(FileFilter:="Excel workbook (*.xls),*.xls", Title:="Open data")
wbThis.Activate
Set rDest = Application.InputBox(Prompt:="Please select the Cell to paste to", Title:="Paste to", Type:=8)
On Error GoTo 0
wbTarget.Activate
Application.CutCopyMode = False
wbTarget.Range("A1").Select
wbTarget.Range("B6:B121").Copy
wbThis.Activate
rDest.PasteSpecial (xlPasteValues)
Application.CutCopyMode = False
wbTarget.Close False
答案 0 :(得分:3)
GetOpenFileName并没有真正打开文件,只是得到它的名字。
尝试Application.Workbooks.Open(TheResultOfGetOpenFileName)
dim FileName as string
FileName = Application.GetOpenFilename(FileFilter:="Excel workbook (*.xls),*.xls", Title:="Open data")
Set wbTarget = Application.Workbooks.Open(FileName)