Я хотел выяснить, в каком порядке VBA оценивает термины внутри выражения.
Я прочитал документ о приоритетном операторе и подумал, что он просто оценит слева направо, если все термины будут оперированы знаком "+". Однако я получаю эти странные результаты.
Option Explicit
Dim x
Sub test()
Debug.Print CreateObject("Scripting.FileSystemObject") _
.GetFileVersion(Application.Path & "\Excel.exe") ' 16.0.12624.20086
x = 0: Debug.Print inc_x + x '(a) 2
x = 0: debug_print inc_x + x '(b) 2
x = 0: Debug.Print x + inc_x '(c) 2 <=== ?
x = 0: debug_print x + inc_x '(d) 2 <=== ?
x = 0: Debug.Print inc_x + 0 + x '(e) 2
x = 0: debug_print inc_x + 0 + x '(f) 2
x = 0: Debug.Print 0 + x + inc_x '(g) 2 <=== ?
x = 0: debug_print 0 + x + inc_x '(h) 1 <=== ???
End Sub
Function inc_x()
x = x + 1
inc_x = x
End Function
Function debug_print(msg)
Debug.Print msg
End Function
Я думал, что (c), (d) и (g) должны печатать 1, но они печатают 2. И это становится еще более странным, когда вы смотрите на ( h) который печатает только один 1.
Может кто-нибудь объяснить, что происходит?
добавил больше шаблонов
Я добавил (i), (j), (k), (l), (m) и (n), что также показывает интересные закономерности. @SJR также научил меня, что указание типа x как Long изменит результат (d).
Option Explicit
Dim x 'As Long 'specifying the type will change the result of (d)
Sub test()
Debug.Print CreateObject("Scripting.FileSystemObject") _
.GetFileVersion(Application.Path & "\Excel.exe") ' 16.0.12624.20086
x = 0: Debug.Print inc_x + x '(a) 2
x = 0: debug_print inc_x + x '(b) 2
x = 0: Debug.Print x + inc_x '(c) 2 <=== ?
x = 0: debug_print x + inc_x '(d) 2 <=== ? (This becomes 1 when x is Long)
x = 0: Debug.Print inc_x + 0 + x '(e) 2
x = 0: debug_print inc_x + 0 + x '(f) 2
x = 0: Debug.Print 0 + x + inc_x '(g) 2 <=== ?
x = 0: debug_print 0 + x + inc_x '(h) 1 <=== ???
x = 0: Debug.Print 100 * inc_x + 10 * x + 1 * inc_x '(i) 122
x = 0: debug_print 100 * inc_x + 10 * x + 1 * inc_x '(j) 112
x = 0: Debug.Print 1000 * x + 100 * inc_x + 10 * x + 1 * inc_x '(k) 2122
x = 0: debug_print 1000 * x + 100 * inc_x + 10 * x + 1 * inc_x '(l) 112
x = 0: Debug.Print 10000 * inc_x + 1000 * x + 100 * inc_x + 10 * x + 1 * inc_x '(m) 13233
x = 0: debug_print 10000 * inc_x + 1000 * x + 100 * inc_x + 10 * x + 1 * inc_x '(n) 11223
End Sub
Function inc_x()
x = x + 1
inc_x = x
End Function
Function debug_print(msg)
Debug.Print msg
End Function