我试图在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
最佳答案
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)