1

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

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" 方法或 With Block 未设置。

任何帮助表示赞赏。

谢谢,

4

1 回答 1

4

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

这是你正在尝试的吗?

注意:我没有做任何错误处理。我相信你可以解决这个问题。

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
于 2012-08-15T23:37:50.117 回答