3

我正在尝试在 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
4

1 回答 1

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)
于 2013-03-26T16:04:17.740 回答