使用VBA将另一个工作簿中的工作表加载到Excel中

时间:2012-08-15 23:26:03

标签: vba excel-vba excel

我正在尝试创建一个子例程,提示用户选择工作簿,然后将所选工作簿的第一个工作表添加为现有(活动)工作簿中的选项卡。然后将新选项卡命名为“数据”。这是我到目前为止使用的代码:

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

此代码似乎无法正常工作,并返回以下错误:

  

“ws.Add”方法或“未设置阻止”。

感谢任何帮助。

谢谢,

1 个答案:

答案 0 :(得分:4)

您已将ws声明为工作表,GetOpenFilename正在返回文件名。我建议您在此link中阅读我的帖子:

这是你在尝试的吗?

注意:我没有做任何错误处理。我相信你可以照顾到这一点。

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