vba excel if函数的条件数组

标签 vba excel

我正在使用 worksheetfunction.averageifs() 和 worksheetfunction.countifs() 函数。

我有一些条件语句指定应查找的条件,因此我只想有一个可以添加新条件的数组,这样就可以代替一系列困惑的条件语句:

If (dep = 0) Then
    sortspg = True
    colcount = .CountIfs(column, "<3", badCol, "1")
    If (colcount > 0) Then
        colavg = .AverageIfs(column, column, "<3", badCol, "1")
        insert = True
    Else
        insert = False
    End If
Else
    colcount = .CountIfs(column, "<3", DepColumn, dep, badCol, "1")

    If colcount > 0 Then
        colavg = .AverageIfs(column, column, "<3", DepColumn, dep, badCol, "1")
        insert = True
    Else
        insert = False
    End If
End If

我可以传递一个数组,例如:

CondArray(column => "<3", DepColumn => dep)
If colCount > 0 Then 
CondArray[] = (badCol => "1")

然后

.CountIfs(CondArray)
.AverageIfs(column, CondArray)

最佳答案

您可以使用 For...Next 循环来设置公式和 Evaluate 函数来构建它。

Sub Build_Formula()
'http://stackoverflow.com/questions/15317466/vba-excel-array-of-criteria-for-if-functions
Dim i As Long, lOutput As Long
Dim strTempArr As String
Dim CondArray() As Variant
Dim StrFormulaBuildUp As String
Dim rng As Range

'Modify constant with applicable formula worksheet function
Const STRFORMULASTART As String = "CountIfs("

'Note used this for test data; edit as applicable
Set rng = Cells.CurrentRegion

'Build array holding conditions; the way the loop is structured is for
'the "COUNTIF" function; modify as necessary
CondArray = Array(rng, "<3")

StrFormulaBuildUp = STRFORMULASTART
'Begin loop to build formula
For i = LBound(CondArray) To UBound(CondArray)
    'Test if value in condition array is a range
    'if yes set the range address to a string
    If TypeName(CondArray(i)) = "Range" Then
        strTempArr = CStr(CondArray(i).Address)
    Else
        'If condtion, then add quote marks
        strTempArr = Chr(34) & CStr(CondArray(i)) & Chr(34)
    End If
    StrFormulaBuildUp = StrFormulaBuildUp & strTempArr & ","
Next i
'Remove extra "," from string and close formula
StrFormulaBuildUp = Left(StrFormulaBuildUp, Len(StrFormulaBuildUp) - 1) & ")"
'Determine forumla value
lOutput = Evaluate(StrFormulaBuildUp)
MsgBox lOutput
End Sub

关于vba excel if函数的条件数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15317466/

相关文章:

excel - 存储添加的结果单元格值,然后每次将其添加到新结果中

Excel 宏/用户窗体 : "For Each" not looping through controls in TabIndex order

vba - Excel VBA : Copy two columns in a different file

excel - 来自列号的vba列地址

vba - 选择其他工作表或工作簿时尝试使用 ThisWorkbook 设置范围值时出现问题

python - 将 excel 数据与 python 或 Excel 连接起来

vba - 通过 VBA 检测复选框的更改

string - VBA 字符串空格 : Preferred Method?

javascript - Visual Basic 和 Javascript 之间的舍入误差

java - 打印结果 XSSFCell.setCellFormula()