[英]Loading a worksheet from another workbook into Excel with VBA
I am attempting to create a subroutine that prompts the user to select a workbook and then adds the first worksheet of the selected workbook as a tab in the existing (active) workbook. 我正在尝试创建一个子例程,提示用户选择一个工作簿,然后将所选工作簿的第一个工作表添加为现有(活动)工作簿中的选项卡。 Then names the new tab "Data". 然后将新选项卡命名为“数据”。 Here is the code I am using so far: 这是我到目前为止使用的代码:
Sub getworkbook()
' Get workbook...
Dim ws As Worksheet
Dim filter As String
Dim targetWorkbook As Workbook
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
ws = Application.GetOpenFilename(filter, , caption)
ws.Add After:=Sheets(Sheets.Count)
ws.Name = "DATA"
End Sub
This code doesn't seem to be working and is returning the following error: 此代码似乎不起作用,并返回以下错误:
"ws.Add" method or With Block not set. “ws.Add”方法或With Block未设置。
Any help is appreciated. 任何帮助表示赞赏。
Thanks, 谢谢,
You have declared ws
as a worksheet and GetOpenFilename
is returning a File name. 您已将ws
声明为工作表, GetOpenFilename
将返回文件名。 I would recommend reading my post in this link : 我建议在这个链接中阅读我的帖子:
Is this what you are trying? 这是你在尝试什么?
Note : I have not done any error handling. 注意 :我没有做任何错误处理。 I am sure you can take care of that. 我相信你可以照顾到这一点。
Sub getworkbook()
' Get workbook...
Dim ws As Worksheet
Dim filter As String
Dim targetWorkbook As Workbook, wb As Workbook
Dim Ret As Variant
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
Caption = "Please Select an input file "
Ret = Application.GetOpenFilename(filter, , Caption)
If Ret = False Then Exit Sub
Set wb = Workbooks.Open(Ret)
wb.Sheets(1).Move After:=targetWorkbook.Sheets(targetWorkbook.Sheets.Count)
ActiveSheet.Name = "DATA"
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.