") a = 10 B = 20 IF a...">

Dynamic operator in VBA. How can I?

How to create a dynamic statement using VBA?

swt = True
op = IIf(swt = True, "<", ">")
a = 10
B = 20
IF a op B then
MsgBox ("a is greater than B")
End If

Obviously this fails, but can anyone make it work?

+4
source share
4 answers

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
+4
source

Use the method Evaluate().

swt = True
op = IIf(swt = True, "<", ">")
a = 10
B = 20
If Evaluate(a & op & B) Then
    MsgBox ("a is greater than B")
End If
+1
source

, : 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.

+1

, , 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
+1
source

Source: https://habr.com/ru/post/1605831/


All Articles