VBA"编译错误:无效或不合格的参考" Application.FileDialog

时间:2015-06-16 16:38:15

标签: excel vba excel-vba

当我尝试运行此VBA宏时,会说"编译错误:无效或不合格的引用"。以下是宏的相关部分:

第一个.Filters.Add with" Excel 2003"被突出显示为违规部分。

我甚至尝试了#34; On Error Resume Next:它没有帮助绕过错误,这让我感到惊讶。

Option Explicit
Sub DataProcessingExperiment7()

'   Reduces CPU intensity + macro execution time since data types can be managed
Application.CalculationxlCalculationManual

On Error Resume Next
'  Declare as strings, as integers, as variants, decDecimals, as Office.FileDialog
Dim strPath, strFileN, strDirN, strCPath, strRangeNOut, strRangeNIn, strTLCorn, strBRCorn, strtemp_name As String
Dim iStartcol, iStartrow, iColNo, iStep, iPlateNo, iRowIn As Integer
Dim vResMatrix() As Variant
Dim decBgrSum, decBgrVal, decVolcorr
Dim fd As Office.FileDialog
'   MEeff = measure of efflux due to crudely purified HDL in scintillation
'   Math operations are fastest with Integers / UIntegers: https://msdn.microsoft.com/en-us/library/ae55hdtk.aspx

'   Start File Explorer to select file containing data
Set fd = Application.FileDialog(msoFileDialogFilePicker)
    Dim vrtSelectedItem As Variant
    **.Filters**.Add "Excel 2003", "*.xls"
    .Filters.Add "Excel 2003 Macro-Enabled", "*.xlsm"
    .Filters.Add "All Files", "*."
With fd
    If .Show = -1 Then
        txtFileName = vrtSelectedItem
        MsgBox "The path is: " & vrtSelectedItem
    End If
'   Excel 2003 is a good filter choice: Excel Viewer, OpenOffice, + Excel versions can open these files
'   If .Show = - 1 user picked at least one file
    Next vrtSelectedItem
    Else
    End If
End With

1 个答案:

答案 0 :(得分:1)

首先,On Error Resume Next不会避免编译错误,因为编译发生在代码开始运行之前:) On Error Resume Next只在代码运行时才有用。

您的错误正在发生,因为您确实拥有所有三条.Filters.Add行的非限定引用。我看到你要做的是什么,要修复它你需要将它们放在With fd语句中。请参阅以下链接以获取更多示例:

https://msdn.microsoft.com/en-us/library/office/ff836226.aspx

Sub UseFileDialogOpen() 

    Dim lngCount As Long 

    ' Open the file dialog 
    With Application.FileDialog(msoFileDialogOpen) 
        .AllowMultiSelect = True 
        .Show 

        ' Display paths of each file selected 
        For lngCount = 1 To .SelectedItems.Count 
            MsgBox .SelectedItems(lngCount) 
        Next lngCount 

    End With

End Sub