VBA 嵌套 WorksheetFunctions 代码中的 IfError 编译错误

Compile Error At IfError in VBA Code of Nested WorksheetFunctions

所以,我是 VBA 的新手,我正在努力学习。我有几个 table 带有紧固件数据,我试图根据主要输入 table 中的内容从中提取信息。我有一个有效的公式,但是当我添加不同的紧固件 tables 时,嵌套的 IF 公式变得不守规矩。我决定尝试将公式转换为 VBA,但出现错误:“编译错误:参数数量错误或 属性 赋值无效。”它出现在 IfError 处。我也可能错误地调用了 table 列。我尝试转换的公式包含在下面。我还没有确定如何最好地设置 If 语句,以便如果用户选择 IFF,它将切换到使用 IFF table,但那是另一个 post.

 Dim tbl_Solid As ListObject
    
    Dim Rep_Fast_Type
    Dim Incoming_Dia
    Dim BP_Max_Dia
    Dim Test_Dia
    Dim Rep_Fast
    Dim Test_Value
    Dim i
    
    Set tbl_Solid = ThisWorkbook.Sheets("Fastener DB").ListObjects("tbl_Solid")
    
    i = 1
    
    Incoming_Dia = [tbl_Input].Cells(i, 2)
    BP_Max_Dia = [tbl_Input].Cells(i, 3)
    Rep_Fast_Type = [tbl_Input].Cells(i, 4)
    
    If Incoming_Dia > BP_Max_Dia Then
            Test_Dia = Incoming_Dia
        Else
            Test_Dia = BP_Max_Dia
    End If
    
'Compile error at IfError in third line.
    If Rep_Fast_Type = "Solid" Then
       Rep_Fast = WorksheetFunction.Index([tbl_Solid].Range("Fastener"), _
                WorksheetFunction.Aggregate(15, 6, WorksheetFunction.IfError( _
                    Rows([tbl_Solid].Range("Fastener")) / ((Test_Dia >= [tbl_Solid].Range("min")) * (Test_Dia <= [tbl_Solid].Range("max"))), _
                        Rows([tbl_Solid].Range("Fastener")) / (Test_Dia <= [tbl_Solid].Range("min")), 1)))
    End If
    
    'To test values
    MsgBox "Incoming diameter is " & Incoming_Dia & vbCrLf & "B/P max diameter is " & BP_Max_Dia & vbCrLf & "Test diameter is " & Test_Dia & vbCrLf & "Repair fastener type is " & Rep_Fast_Type & vbCrLf & "Repair Fastener is " & Rep_Fast

旧Excel公式:

=IF([@[rep type]]="Solid",INDEX(tbl_Solid[[#All],[Fastener]],AGGREGATE(15,6,IFERROR(ROW(tbl_Solid[Fastener])/(([@diameter]>=tbl_Solid[min])*([@diameter]<=tbl_Solid[max])),ROW(tbl_Solid[Fastener])/([@diameter]<=tbl_Solid[min])),1)),IF([@[rep type]]="IFF",INDEX(tbl_IFF[[#All],[Fastener]],AGGREGATE(15,6,IFERROR(ROW(tbl_IFF[Fastener])/(([@diameter]>=tbl_IFF[min])*([@diameter]<=tbl_IFF[max])),ROW(tbl_IFF[Fastener])/([@diameter]<=tbl_IFF[min])),1))))

数据截图

只是括号放错了:

替换此行:

Rows([tbl_Solid].Range("Fastener")) / (Test_Dia <= [tbl_Solid].Range("min")), 1)))

为此:

Rows([tbl_Solid].Range("Fastener")) / (Test_Dia <= [tbl_Solid].Range("min"))), 1))

尽管如此,我建议使用 With statement 来包装公式,即:

With WorksheetFunction
    Rep_Fast = .Index([tbl_Solid].Range("Fastener"), _
        .Aggregate(15, 6, .IfError( _
            Rows([tbl_Solid].Range("Fastener")) / _
                ((Test_Dia >= [tbl_Solid].Range("min")) * (Test_Dia <= [tbl_Solid].Range("max"))), _
                    Rows([tbl_Solid].Range("Fastener")) / (Test_Dia <= [tbl_Solid].Range("min"))), 1))
End With

请注意,此答案仅针对给出编译错误的语法,未对公式输出进行测试。