excel - 在 VBA 函数中传递 Excel 范围,作为数组处理,并返回结果

标签 excel vba

我有一个 Excel 工作表,其中有一列中有一些字符串。有时所有条目都相同,有时则不同:
enter image description here
enter image description here
我编写了一个函数来将范围作为参数传递:

=Dent_WG(A1:A6)
VBA 函数应确定哪种情况为真(所有条目 = “Al”,或至少一个条目 = “Ag”),然后分别返回 0 或 12:
Function DentWG(WG_Mat As Range) As Single

    Dim dat As Variant, rw As Variant, temp As Single
    dat = WG_Mat
    temp = 0
    
    For rw = LBound(dat, 1) To UBound(dat, 1)
        If dat(rw, 1) = "Ag" Then
            temp = 12
        End If
    Next

    If temp = 12 Then
        DentWG = 12
    Else
        DentWG = 0
    End If

End Function
但是,该函数始终返回 0,即使对于“Ag”出现在范围内的第二种情况也是如此。我确定我未能正确地将范围转换为数组或将预期的逻辑正确应用于该数组。

最佳答案

从你的问题...

The VBA function should determine which case is true (all entries = "Al", or at least one entry = "Ag"), then return 0 or 12 respectively:



这就是你需要的。
Function DentWG(WG_Mat As Range) As Long 
    Dim ClCount As Long

    ClCount = WG_Mat.Cells.Count

    If Application.WorksheetFunction.CountIf(WG_Mat, "Al") = ClCount Then
        DentWG = 0
    ElseIf Application.WorksheetFunction.CountIf(WG_Mat, "Ag") > 0 Then
        DentWG = 12
    End If
End Function

使用公式可以实现相同的目的
=IF(COUNTIF(A1:A6,"Al")=(ROWS(A1:A6)*COLUMNS(A1:A6)),0,IF(COUNTIF(A1:A6,"Ag") > 0‌​,12,""))
如果它始终为 1 列,则不需要 *COLUMNS(A1:A6) .这会做。
=IF(COUNTIF(A1:A6,"Al")=ROWS(A1:A6),0,IF(COUNTIF(A1:A6,"Ag") > 0,12,""))
截图

enter image description here

关于excel - 在 VBA 函数中传递 Excel 范围,作为数组处理,并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21663348/

相关文章:

vba - 如何在VBA中对变量范围内的值求和?

excel - 用于永久启用 MACROS 的 QTP 代码

excel - 范围名称中的 VBA、& 符号和循环

xml - 在导入 Excel 之前对 XML 应用 XSLT

list - 动态范围表中的唯一列表,可能有空白

excel - VBA将html表格数据复制到excel工作表

java - APACHE POI autoSizeColumn 与 useMergedCells 太慢

excel - 如何在不设置引用的情况下从另一个 Office 应用程序打开 Excel?

forms - 在 VBA (Excel 2007) 中关闭表单时执行代码

vba - 非 volatile UDF总是重新计算