打开一个extern工作簿并返回一个工作表不起作用

时间:2014-12-17 16:26:14

标签: vba excel-vba excel

我的错误号码是1004:

Function getWorksheet(SheetNumber As Integer) As Worksheet

    Dim workbook As workbook
    Dim file As Variant

    file = ShowFileDialogAndFindFile

    Set workbook = Workbooks.Open(file, True, True)

    getWorksheet = workbook.Worksheets(SheetNumber)

End Function

Function ShowFileDialogAndFindFile() As Variant

    Dim fd As FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    Dim vrtSelectedItem As Variant

    With fd

        If .Show = -1 Then

            For Each vrtSelectedItem In .SelectedItems

                ShowFileDialog = vrtSelectedItem

            Next vrtSelectedItem
        Else
        End If
    End With
    Set fd = Nothing

End Function

我正在从另一个模块调用:

Dim sheetExtern As Worksheet
sheetExtern = getWorksheet(1)

1 个答案:

答案 0 :(得分:0)

您需要使用关键字Set来执行此操作。基本上是:

无法使用

Dim sheetExtern As Worksheet
sheetExtern = getWorksheet(1)

应该工作(假设其余功能正常):

Dim sheetExter As Worksheet
Set sheetExtern = getWorksheet(1)

除了本机类型(如String,Integer,Double)之外,当您想在VBA中设置对象时,您需要先使用关键字Set

确定:a = 2(原生类型整数) 好的:a = "hello"(本机类型字符串) KO:a = New Collection(必须设置集合,即Set a = New Collection)。

值得回答阅读here和背景问题here