Excel 2010 VBA:设置使用msoFileDialogOpen打开工作簿时出现错误91

时间:2018-08-02 12:33:44

标签: excel vba

我到处都是关于FileDialogOpen和错误91的,我知道我有一个变量声明问题,但无法弄清楚代码中出了什么问题

Dim Ex As Excel.Application
Dim wb As Workbook
Dim openDialog As Office.FileDialog
Dim filename As String

Set openDialog = Application.FileDialog(msoFileDialogOpen)
With openDialog
    .Filters.Clear
    .Filters.Add "Excel Files", "*.xlsx"
    .AllowMultiSelect = False
    .InitialFileName = "Path_to_open"
    .Title = "Sélectionnez le fichier"
End With

If openDialog.Show = False Then
    MsgBox "Impossible de mettre à jour sans le fichier", vbOKOnly, "ERREUR"
    Exit Sub
End If

filename = openDialog.SelectedItems(1)
Workbooks.Open (filename)
filename = Mid(filename, 4, Len(filename) - 1)
Set wb = Ex.Workbooks.Open(filename, True, False)

错误91发生在我设置wb的最后一行,以后需要在代码中用于工作簿计算。其余代码运行平稳。

1 个答案:

答案 0 :(得分:1)

将行更改为:

Set wb = Workbooks.Open(filename, True, False)


Set wb = Ex.Workbooks.Open(filename, True, False)不起作用,因为Ex仅在Dim Ex As Excel.Application中声明,但未在此处初始化。