2

I know the following is possible in vba:

If Len(str) Then

Len(str) will evaluate to false if Len(str) is 0, true otherwise.

What are the exact conversion rules for vba? Please provide a link to official documentation if possible.

Roland
  • 7,525
  • 13
  • 61
  • 124
  • 2
    `Len()` returns an integer value, not a boolean. Yes, `False` in VBA is a zero, but it is not in good form to code in this manner. – braX Oct 04 '17 at 12:48

2 Answers2

2

A boolean variable can have only two states, True and False. That's true in all programming languages (except if a nullable datatype exists, eg bool? in C# where the variable can have also the value null signaling it is not defined).

In VBA, a boolean is stored as 16-bit integer. False is defined as 0 and True as -1. Thats similar in other languages, simply because 0 has all bits set to 0 and -1 has all bits set to 1. But this is an implementation detail and your programming should not care about it. You deal with True and False and Boolean algebra using AND, OR and NOT.

Implicit conversion rules are straight forward: Numeric data types are converted to boolean False if they are 0 and to True in all other cases (that is, if the value has any bit set to 1). Converting a boolean value to a number results in 0 resp. -1.

Dim i As Integer
Dim b As Boolean    
i = 3
b = i   ' Implicit conversion from 3 to TRUE
i = b   ' Implicit conversion from TRUE to -1

Strings are converted to numbers first, and if that fails, you get a runtime error. Dates are implemented as numbers (Double) in VBA, so every date/time is True except the date+time that is represented as 0 (that is 30 Dec 1899 00:00)

But from my point of view (and >30 years of programming), implicit conversions are evil and should be avoided. They are source of numerous errors, they lead to code that is harder to read - and there is simply no reason to rely on implicit conversations. There is no reason to write If len(str) Then. You want to check if the length of a string is greater than 0, so write it: If len(str) > 0 Then. Always.

Have a look to the following example: Obviously, the VBA runtime need to execute an implicit conversion, but can you tell the outcome?

Dim i As Integer
Dim b As Boolean  
i = 3
b = i
If b = i Then Debug.Print "B=I"

Here you can find the official documentation from Microsoft: https://learn.microsoft.com/en-US/office/vba/language/reference/user-interface-help/boolean-data-type

FunThomas
  • 23,043
  • 3
  • 18
  • 34
  • 2
    *A boolean variable can have only two states ... an implementation detail and your programming should not care about it* - unless you [have to](https://stackoverflow.com/q/59310779/11683). – GSerg Jan 20 '21 at 11:40
  • @GSerg: Good catch - was not aware about it. Frankly, this seems to be a bug in VBA (and I am usually not that quick with such a statement), because the result in that example manage to write a `1` into a boolean variable - and that's against it's definition. – FunThomas Jan 20 '21 at 11:53
  • InputBox returns False if cancelled: [Microsoft documentation](https://learn.microsoft.com/en-us/office/vba/api/excel.application.inputbox). So what's the road from click Cancel on InputBox to return "Falsch" string [german problem here on SO](https://stackoverflow.com/questions/55453256/vba-inputbox-and-cancel-button)? How regional setting are involved into this ridiculous result or/and casting? Bool<->Long casting is quite obvious here, but what about Bool<-> String like False = "False" and given "Falsch" case? – Rafał B. Jan 21 '21 at 12:47
  • Problem with the InputBox that is returns either a boolean value (False) or a string containing whatever was entered. Read the result into a Variant and check the VarType (see accepted answer) so that you can distinguish between Cancel and entering something like "0". This avoids the implicit conversion from a boolean into a string. – FunThomas Jan 21 '21 at 12:55
  • I know the solution in that case. I am just asking HOW could be False casted to string "Falsch" it's very strange to me... Is Bool->String casting documented or not? BTW thanks for your effort. – Rafał B. Jan 21 '21 at 13:03
  • I guess the implicit conversion result within VBA is the same as using it explicitly (`cStr`), and that should always result in the English terms as VBA is not language dependent. However, as the called function is a method of the `Application`-object (which is Excel, not VBA), maybe the conversion is done already within the function. But that's only guessing, I cannot test it because although I live in Germany, my Office is English. – FunThomas Jan 21 '21 at 13:19
  • @RafałB. That question appears to be based on a wrong premise. Pressing Cancel on `Application.InputBox` returns Variant/Boolean, not a string. – GSerg Jan 21 '21 at 13:33
  • @FunThomas `CStr` is specifically language-dependent and will use the current locale's number and/or date formatting. It does not, however, attempt to localise True and False. – GSerg Jan 21 '21 at 13:34
  • @GSerg When the 'answer' variable (ans = InputBox()) is String type (not Variant), then we get ans = "False" after cancel. But someone can get "Falsch" here. Isn't it implicite casting from boolean (False)? If my question would be InputBox-related I wouldn't ask in "What are the implicit type conversion rules in vba?" thread I think. – Rafał B. Jan 21 '21 at 13:38
  • @RafałB. It is. And it uses `CStr(False)`, which returns `"False"` even in non-English Excel on non-English locale. If you have access to a system where `CStr(False)` produces something else, I would be willing to know about that. – GSerg Jan 21 '21 at 13:43
  • I've just heard about this problem on one Polish Excel board. It sounded incredible for me too (!) so I searched over the internet and found similar thread on SO, that I've linked above. That's why I've started bounty because I cannot get to understand what's happening here. I'll ask the user experiencing a problem to check what MsgBox VBA.CStr(False) shows on his PC. – Rafał B. Jan 21 '21 at 13:54
  • 1) MsgBox VBA.CStr(False) shows string *False* in the test described above 2) someone gave a screenshot from *Excel 2007 VBA Programmer's Reference* by John Green et al. which have a slightly suggestion that it DOES NOT use inbuilt Cstr such and it returns bool name taken from *Windows Regional Settings* not VBA itself like running `MsgBox Prompt:=False`. Ok, and my final conclusion at the moment is: it seems that the casting result may depends on system, this implicit conversion (assignation boolean to string) should be avoid because is not reliable and also IS NOT documented by Microsoft. – Rafał B. Jan 21 '21 at 17:55
-2

I came across this in a recent textbook I was reading on C++ - I'll add a link at the end. Although a different language, both have similarities to some degree. One of these similarities is what you call 'implicit type conversion' or more technically, type casting.

For any Boolean expression in your project when you compile your VBA project (Debug > Compile VBAProject) any nonzero value will be treated as the value true and will treat the value 0 as false. Essentially this comes down to the how the compiler treats these statesments and also to operator precedence rules as well as boolean expression rules.

For further reading please see below links:

  1. Operator precedence
  2. Boolean data type

In C++ (as far as I am aware) this term is called copy initialisation, you can read more here:

  1. Copy initialization

The book that brought this deep thought recently:

Problem Solving with C++: The Object of Programming

I know this doesn't necessarily answer your question, but hopefully some of the references help.

Dean
  • 2,326
  • 3
  • 13
  • 32
  • 2
    Be careful, your links lead to VB.Net, not VBA – FunThomas Jan 20 '21 at 11:05
  • 1
    @Dean no one gave good answer to my "bounty". FunThomas and GSerg narrowed down title's topic only to the simplest well-documented cases. Even question's authors Roland wrote that "The question is about any two types". But I must choose the answer to reward. Your answer isn't good too, but you linked some very interesting off-topic links and the bounty is yours. – Rafał B. Jan 25 '21 at 16:24