我有一个 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”出现在范围内的第二种情况也是如此。我确定我未能正确地将范围转换为数组或将预期的逻辑正确应用于该数组。
最佳答案
从你的问题...
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,""))
截图
关于excel - 在 VBA 函数中传递 Excel 范围,作为数组处理,并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21663348/