我可以在函数参数中使用"If"语句吗?

AGr*_*icz 2 arrays excel vba excel-vba

我想在我的VBA代码中使用IF语句,我正在调用一个Function并向它传递两个参数.我需要IF语句的原因是因为参数是我传递给函数的数组对象.这是包含问题的代码的缩写:

For i = 1 To UBound(FilterArray)
    For j = LBound(ptsheets, 1) To UBound(ptsheets, 1)
        Filter_PivotField_Master _
            pvtField:=ThisWorkbook.Worksheets(ptsheets(j, 1)).PivotTables(ptsheets(j, 2)).PivotFields(FilterArray(i, 1)), _
            FilterTypeArray:= If FilterArray(i, 2) = 1 Then
                                InvCodeArray
                                Else
                                BoardMonthArray
                                End If
    Next j
Next i
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我正在遍历ptsheets数组,并且对于每个条目,我正在调用Filter_PivotField_Master函数.该函数需要两个输入(pivotfield和用于过滤的字符串数组).名为"FilterArray"的数组只包含传递给函数所需的信息.因为我似乎无法在"FilterArray"中存储字符串数组(InvCodeArray或BoardMonthArray),所以我想使用这个IF语句在两个数组之间进行选择,如果FilterArray(i,2)等于"1"或不.这里有"IF"声明选项吗?

Mat*_*don 5

不要那样做.从内部循环中提取方法/过程,然后对其进行参数化.

    For j = LBound(ptsheets, 1) To UBound(ptsheets, 1)
        Filter_PivotField_Master _
            pvtField:=ThisWorkbook.Worksheets(ptsheets(j, 1)).PivotTables(ptsheets(j, 2)).PivotFields(thePivotField), _
            FilterTypeArray:= theFilterType
    Next j
Run Code Online (Sandbox Code Playgroud)

然后让调用代码(外部循环)实现条件逻辑,确定给出它的参数.

Dim thePivotField
Dim theFilterType

For i = 1 To UBound(FilterArray)
    thePivotField = FilterArray(i, 1)
    If FilterArray(i, 2) = 1 Then
        theFiltertype = InvCodeArray
    Else
        theFilterType = BoardMonthArray
    End If
    TheExtractedMethod i, thePivotField, theFilterType
Next i
Run Code Online (Sandbox Code Playgroud)

您的代码将更容易遵循 - 并进行调试.


在一个相关的说明中,我做了一些假设只是为了让你的代码片段用Option Expliciton(而IIf不是非法的If...Else块)编译,而Rubberduck的最后一个版本(v1.4.3)正确地将选择的内部循环提取到它自己的方法中:

Rubberduck的Extract Method重构工具

Rubberduck 1.4.3中存在一些已知错误,而v2.0即将推出,但我认为这可能会让您感兴趣.我不知道VBA的任何其他重构工具.请注意,Option Explicit这对于它来说几乎是一个很难的要求,因为Rubberduck 无法处理声明并且无法解析未声明的变量.

免责声明:我写了这个重构工具.