Dynamic operator in VBA. How can I?
Use the basic string concatenation methods to build a simple mathematical formula that takes the operator as a string character. After the formula is built from parts of the string, it can be solved using Application Evaluate .
Dim swt As Boolean, op As String
Dim a As Long, b As Long
swt = False
op = IIf(swt, "<", ">")
a = 10
b = 20
If Application.Evaluate(a & op & b) Then
MsgBox ("a is " & IIf(swt, "less", "greater") & " than b")
Else
MsgBox ("a is " & IIf(swt, "greater than or equal to", "less than or equal to") & " b")
End If
, : VBA , , :
If a op B Then
If, :
If [BoolExp] Then
..., bump a op B , a , op , B - , 't [BoolExp] - , .
.
swt = True
op = IIf(swt = True, "<", ">")
IIf : IIf([BoolExp], [ValueStmt], [ValueStmt]) - swt True, . , op :
op = IIf(swt, "<", ">")
, , op String, .
Application.Evaluate, - VBA, Office,
If swt Then
If a < b Then msg = "a is smaller than b"
Else
if a > b then msg = "a is greater than b"
End If
MsgBox msg
, , a = b.
, , VBA infix.
, , , , sub. , C ( infix). qsort, . - VBA.
VBA , Application.Run ( , Application.Evaluate) , . , , , , , , , :
Public AZ As Boolean 'a global sort-order flag
Function compare(x As Double, y As Double) As Boolean
compare = IIf(AZ, (x < y), (y < x))
End Function
, Application.Run , , , , , , . , . :
Function Most(comp As String, items As Variant) As Variant
Dim i As Long, candidate As Variant, item As Variant
Dim lb As Long, ub As Long
lb = LBound(items)
ub = UBound(items)
candidate = items(lb)
For i = lb + 1 To ub
item = items(i)
If Application.Run(comp, candidate, item) Then
candidate = item
End If
Next i
Most = candidate
End Function
, :
Sub test()
Dim A As Variant
A = Array(3, 6, 2, 8, 11, 15, 1, 10)
AZ = True
Debug.Print Most("compare", A) 'prints 15
AZ = False
Debug.Print Most("compare", A) 'prints 1
End Sub