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

我想在我的VBA代码中使用一个IF语句,我调用一个函数并传递给它两个参数。 我需要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 

正如你所看到的,我正在循环访问ptsheets数组,并为每个条目调用Filter_PivotField_Master函数。 该函数需要两个input(一个pivotfield和一个string数组进行过滤)。 名为“FilterArray”的数组仅包含传递给函数所需的信息。 因为我似乎无法在“FilterArray”中存储string数组(“InvCodeArray”或“BoardMonthArray”),所以我想使用这个IF语句来select基于FilterArray(i,2)是否等于“1”或不。 在这里可以使用“IF”语句选项吗?

不要这样做。 从内部循环中提取一个方法/程序,然后参数化它。

  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 

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

 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 

您的代码将更容易遵循 – 并进行debugging。


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

Rubberduck的Extract Method重构工具

Rubberduck 1.4.3有一些已知的bug,v2.0即将推出,但我认为这可能会让你感兴趣。 我不知道任何其他的VBA重构工具。 请注意, Option Explicit对于这个工作来说非常困难,因为Rubberduck在声明中运行 ,并且不能parsing未声明的variables。

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

为此,请使用即时IF(IIF)。

 FilterTypeArray = IIF(FilterArray(i, 2) = 1, InvCodeArray, BoardMonthArray)