vba 打开用户指定的 Excel 工作簿并将数据范围复制到另一个工作簿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15641558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 20:16:14  来源:igfitidea点击:

Open user specified Excel workbook and copy data range to another workbook

excelexcel-vbavba

提问by user2033485

I am trying to run a macro in Excel where the user chooses a file to open and the macro will copy a range from that workbook and paste it to a user specified cell in the original workbook. My attempt at the code is shown below. I have "wbThis" as the original workbook to be pasted to and "wbTarget" as the workbook that is being opened and copied from. When I run the code, I can choose what file I want to open but it gives an error saying "Object required" and doesn't proceed further into copying and pasting.

我试图在 Excel 中运行一个宏,用户选择一个文件打开,宏将从该工作簿中复制一个范围并将其粘贴到原始工作簿中用户指定的单元格中。我对代码的尝试如下所示。我将“wbThis”作为要粘贴到的原始工作簿,将“wbTarget”作为正在打开和复制的工作簿。当我运行代码时,我可以选择我想要打开的文件,但它给出了一个错误,提示“需要对象”并且不会进一步进行复制和粘贴。

Is there a way to use Workbook.Open instead of Application.GetOpenFilename but still have the user be able to choose what file to open?

有没有办法使用 Workbook.Open 而不是 Application.GetOpenFilename 但仍然让用户能够选择要打开的文件?

Thank you for your help.

感谢您的帮助。

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

采纳答案by Daniel M?ller

GetOpenFileName does not really opens a file, just gets it's name. Try doing Application.Workbooks.Open(TheResultOfGetOpenFileName)

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)