【问题标题】:Pass Excel Range in VBA Function, Process as Array, and Return Result在 VBA 函数中传递 Excel 范围,作为数组处理,并返回结果
【发布时间】:2014-03-06 23:11:23
【问题描述】:

我有一个 Excel 工作表,其中有一列中有一些字符串。有时所有条目都相同,有时则不同:

我写了一个函数将范围作为参数传递:

=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”出现在范围内的第二种情况也是如此。我确定我未能正确地将范围转换为数组或将预期的逻辑正确应用于该数组。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    从你的问题...

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

    这就是你需要的。

    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,""))

    屏幕截图

    【讨论】:

    • @Siddharth Rout:+1 并检查。感谢这两个解决方案。他们都对我很好。我自己的解决方案(我在上面已经更正)也有效。我看到您的解决方案调用 Application.WorksheetFunction。在我的简单应用程序中,资源不是问题,但一般来说:在 VBA 代码中调用 Application.WorksheetFunction 是否比严格使用 VBA 方法更耗费资源?
    • @assylias:相反,感谢您纠正我的循环计数器。
    • 完成了——我只是一个休闲的 vba-er,你可以与专业人士区分! ;-)
    【解决方案2】:

    您实际上并不需要 UDF。你可以说:

    =IF(COUNTIF(A1:A6,"Ag")>=1,12,0)

    【讨论】:

    • + 1 对于非 VBA 解决方案 :) 但是您错过了一部分 which case is true (all entries = "Al", or at least one entry = "Ag")
    • 你还是忘记了“Al”:)
    • @SiddharthRout 是的,但是从他的代码中我假设 OP 假设输入是可靠的“Ag”或“Al”。诚然,这是很多假设:-)
    • 查看附件截图。而这部分问题The VBA function should determine which case is true (all entries = "Al", or at least one entry = "Ag"), then return 0 or 12 respectively:
    • I assumed that the OP assumed that the inputs were reliably "Ag" or "Al". Admittedly, that's a lot of assuming :-) BTW 阅读问题的第二句...Sometimes all of the entries are the same, and sometimes not :)
    【解决方案3】:

    这对我有用:

    Function DentWG(WG_Mat As Range) As Single
        Dim result As Single, cl as Range
        result = 0
    
        For Each cl In WG_Mat
            If cl = "Ag" Then
                DentWG = 12
                Exit Function
            End If
        Next cl
    
        DentWG = result
    End Function
    

    【讨论】:

    • 这也没有回答问题。
    • @Alex P:对我不起作用,也许是因为 cl 没有声明?
    • 从循环中退出函数...真的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多