我想要一个 excel 的简写VBA Application.WorksheetFunction。到目前为止,它在下面的代码中运行良好,但现在我想评估一个类似于以下内容的函数:
=IFERROR(MAX(M$2:M$64)*BINOM.DIST($W2,COUNTIF(M$2:M$64,"<"&MAX(M$2:M$64))-COUNTIF(M$2:M$64,"<"&1),0.5,FALSE),"")
Run Code Online (Sandbox Code Playgroud)
Application.WorksheetFunction在我调用的每个函数前使用会非常混乱。请告诉我如何使用速记。
=IFERROR(MAX(M$2:M$64)*BINOM.DIST($W2,COUNTIF(M$2:M$64,"<"&MAX(M$2:M$64))-COUNTIF(M$2:M$64,"<"&1),0.5,FALSE),"")
Run Code Online (Sandbox Code Playgroud)
一个 with 语句在这里是理想的,例如
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下
Range("M" & i) = Application.WorksheetFunction.CountIf(Range("A2:A" & lengthRows), "<" & (Cells(i, "G").Value + 0.25))
Range("N" & i) = Application.WorksheetFunction.CountIf(Range("B2:B" & lengthRows), "<" & (Cells(i, "G").Value + 0.25))
Range("O" & i) = Application.WorksheetFunction.CountIf(Range("C2:C" & lengthRows), "<" & (Cells(i, "G").Value + 0.25))
Range("P" & i) = Application.WorksheetFunction.CountIf(Range("D2:D" & lengthRows), "<" & (Cells(i, "G").Value + 0.25))
Run Code Online (Sandbox Code Playgroud)
变成:
With Application.WorksheetFunction
Range("M" & i) = .CountIf(Range("A2:A" & lengthRows), "<" & (Cells(i, "G").value + 0.25))
Range("N" & i) = .CountIf(Range("B2:B" & lengthRows), "<" & (Cells(i, "G").value + 0.25))
Range("O" & i) = .CountIf(Range("C2:C" & lengthRows), "<" & (Cells(i, "G").value + 0.25))
Range("P" & i) = .CountIf(Range("D2:D" & lengthRows), "<" & (Cells(i, "G").value + 0.25))
End With
Run Code Online (Sandbox Code Playgroud)
编辑(感谢@Wolfie):您还可以定义一个WorksheetFunction对象,并在With块之外使用它。例如:
Dim WF As WorksheetFunction
Set WF = Application.WorksheetFunction
Range("M" & i) = WF.CountIf(Range("A2:A" & lengthRows), "<" & (Cells(i, "G").value + 0.25))
' < etc. >
Run Code Online (Sandbox Code Playgroud)
附加请求,iferror 用例:
Sub test()
With Application.WorksheetFunction
MsgBox (.IfError(ActiveCell.Value, "Error"))
End With
End Sub
Run Code Online (Sandbox Code Playgroud)
附加请求,错误处理:
With Application.WorksheetFunction
On Error Resume Next
For i = 2 To lengthRows
Err.Clear
Range("M" & i) = maxfew * .BinomDist(Cells(i, "M").Value, numtrialsfew, 0.5, False)
If Err > 0 Then Range("M" & i) = ""
Next i
On Error GoTo 0
End With
Run Code Online (Sandbox Code Playgroud)