In the message boxes all the time displays 1. But if you remove the first line (the line with the division) from the first function, everything is fine.

What is it connected with and what should I do? Help me please.

Function char_in_2(x As Integer) x = x \ 2 char_in_2 = x End Function Function nayti(dlina As Integer) Dim i As Integer i = 0 Do While char_in_2(i) <> dlina i = i + 1 MsgBox i Loop nayti = i End Function Sub Test1() MsgBox nayti(7) End Sub 

    2 answers 2

    Integer - integer is passed to the function. x = x \ 2 - the number is entered into the variable with the fractional part dropped. With i = {0; 1} char_in_2 = 0 .

    But that is not all. The variable x, passed from the nayti function, changes its value and 0 (zero) is returned to the loop. Because in cycle i never rises above 1, the cycle becomes infinite (7 never appears).

    '-----------------------

    In VBA, variables are passed to a function as ByRef or ByVal .

    By default, ByRef is a reference to a value that can be changed during the operation of the function.

    ByVal - passing a copy of a variable to a function.

    Conclusion: do not use the same variable names (transmitted and working in the function), if you do not intend to change the transmitted data. Sometimes it is useful to explicitly indicate what is being transmitted:

     Function char_in_2(ByVal k As Integer) 
    • Thank you very much! I have one more question: are these VBA quirks? Just for example, if in C ++ I pass the value of a variable to a function and this function already inside its body changes the value of the passed variable, then in the body from which I called the function, the value of the passed variable will not change. - zavullon
    • Added in response. - vikttur

    Do not change the argument variable inside the called function.

     Function char_in_2(x As Integer) as Integer Dim x2 as Integer x2 = x \ 2 char_in_2 = x2 End Function 
    • This is in the previous answer (see. "Conclusion:") - vikttur