From VB6 to Basic4android

nfordbscndrd

Well-Known Member
Licensed User
Longtime User
VB6 to B4A Conversion Table

B4A features which VB6 doesn't have are not listed. Just go to the HelpViewer for those.

Updated Feb.24, 2011:
-----------------------
B4X:
VB6                      B4A
===                      ===
Global Const x=1    Dim x: x = 1
Control - Events    Generate Members

Dim b as Boolean:
If b then...        If b = True Then...  (You must have the "= True".)
a = a + b           If b = True Then a = a - 1
                       Boolean's value cannot be used in a math function in B4A.
                       This is probably better style anyway.

The complete file:

B4X:
This file is primarily for reference when converting Visual Basic
source code to B4A.

  VB6                  B4A
  ===                  ===
controls            Views  (button, edittext, label, etc.)
In the VB6 code window, the top left drop-down list contains all
the controls you have placed in the current form and the right list
contains all the events for each control.  The equivalen in B4A can
be found by clicking on Designer - Tools - Generate Members. Once
you have created Subs in the program coding window, the tab "Modules"
on the right side will list each of the Subs.

Dim Array(n)        Dim Array(n+1)
While "n" is the last index number in VB6, it indicates the number
of array elements when used in B4A. For example, to Dim an array
with 32 elements in VB6, you would have Dim A(32) while to convert
this to B4A, you need to change it to Dim A(33).

Dim b as Boolean:
If b then...        If b = True Then...  (You must have the "= True".)
a = a + b           If b = True Then a = a - 1
                       Boolean's value cannot be used in a math function in B4A.

ReDim Array()       Dim Array() -- to clear an array, just Dim it again.

Global Const x=1    Dim x As Int: x=1

Do [Until/While]    same
Loop [Until/While]  Loop  [Until/While not allowed.]
For - Next          same
Exit Do/For         Exit
If - Then - Else    same, except VB's ElseIf is "Else If" in B4A

   ---              Continue [Skips to Next in For-Next loop]
                        For i = 1 to 6
                           If i = 4 Then Continue
                           ...optional code...
                           ListView1.AddSingleLine(i & ".")
                        Next

Colors:
L1.BackColor =      L1.Color = Colors.Red
    vbRed
L1.ForeColor =      L1.TextColor = Colors.Black
    vbBlack

DoEvents            same

Format()            NumberFormat & NumberFormat2 [see documentation]

InputBox($)         InputList(Items as List, Title, CheckedItem as Int) as Int
                        Shows list of choices with radio buttons. Returns index.
                        CheckedItem is the default.
                    InputMultiList(Items as List, Title) As List
                        Usere can select multiple items via checkboxes.
                        Returns list with the indexes of boxes checked.
MsgBox "text"       MsgBox("text", "title")
i=MsgBox()          MsgBox2(Message, Title, Positive, Cancel, Negative, Icon) as Int
                        Displays three buttons with text to display for buttons
                           (Positive, Cancel, Negative)
                        Icon is displayed near the title and is specified like:
                           LoadBitmap(File.DirAssets, "[filename].gif")
   ---              ToastMessageShow(text, b) [where b=True for long duration]

Rnd is < 1          Rnd(min, max) is integer >= min to < max
Round(n)            same, or Round2(n, x) where x=number of decimal places

Calling a sub:
SubName x, y        SubName(x, y)

Sub SubName()       Sub SubName() As Int/String/etc. -- a Global variable cannot be
                       a parameter.
Function FuncName() Sub FuncName() with Return [value] at the end (still have
                       End Sub though)
Exit Sub            Return
Exit Function       Return [value]
A Sub in B4A is more like a Function in VB6 except that a value is not assigned to
                       the Sub's name.
Instead, a value is sent via the Return command, as shown above.


Select Case [expr]  Select [value]

i = Val(string)     If IsNumber(string) Then i = string Else i = 0 --
                    An attempt to use i=string "throws an exception" if the string is
                    not numbers.

control.SetFocus    view.RequestFocus

n / 0 : error       n / 0 = 2147483647 -- B4A does not "throw an exception" for
                       division by 0, but it does return 2147483647 no matter
                       what the value of "n" is.

t = Timer           t = DateTime.Now ' Ticks are number of milliseconds since 1-1-70


TabIndex:
--------
In VB, TabIndex can be set to control the order in which controls get focus
when Tab is pressed. According to Erel, in B4A:

"Android handles the sequence according to their position. You can set
EditText.ForceDone = True in all your EditTexts. Then catch the
EditText_EnterPressed event and explicitly set the focus to the next
view (with EditText.RequestFocus).


Setting Label Transparency:
--------------------------
Properties - Back Style        Designer - Drawable - Alpha


Constants:
---------
""                  Quote = Chr$(34)
vbCr                CRLF = Chr$(13)
vbCrLf              none


String "Members":
----------------

VB6 uses a character position pointer starting with 1.
B4A uses a character Index pointer starting with 0.

        VB6                        B4A
Mid$("abcde", 1, 1) = "a" = letter array index 0
Mid$("abcde", 2, 1) = "b" = letter array index 1
Mid$("abcde", 3, 1) = "c" = letter array index 2
Mid$("abcde", 4, 1) = "d" = letter array index 3
Mid$("abcde", 5, 1) = "e" = letter array index 4

     VB6                               B4A
     ===                               ===
Mid$(text, n, 1)                    text.CharAt(n-1)
Mid$(text, n)                       text.SubString(n-1)
Mid$(text, n, x) [x=length wanted]  text.SubString2(n-1, n+x-1) [n+x-1=end position]

Mid$(text, n, x) = text2            text = text.SubString2(0, n-2) & _
                                           text2.SubString2(0, x-1) & _
                                           text.SubString(n-1 + z)  where...
                                             z = Min(x, text2.length)

Left$(text, n)  [n=num.of chars.]   text.SubString2(0, n)
Right$(text, n)                     text.SubString(text.Length - n + 1)
If a$ = b$...                       If a.CompareTo(b)...
If Right$(text, n) = text2...       If text.EndsWith(text2)...
If Left$(text, n) = text2...        If text.StartsWith(text2)...
If Lcase$(text) = Lcase$(text2)...  If text.EqualsIgnoreCase(text2)...
x = Len(text)                       x = text.Length
text = Replace(text, str, str2)     text.Replace(str, str2)
Lcase(text)                         text.ToLowerCase
Ucase(text)                         text.ToUpperCase
Trim(text)                          text.Trim
  (no LTrim or RTrim in B4A)
Instr(text, string)                 text.IndexOf(string)
Instr(int, text, string)            text.IndexOf2(string, int)
                                       Returns -1 if not found.
                                       Returns char. index, not position.
                                       Starts search at "int".
If Lcase$(x) = Lcase$(y)...         If x.EqualsIgnoreCase(y)...
text = Left$(text, n) & s &         text.Insert(n, s)
          Right$(Text, y)
Asc(s) [where s = a character]      same


Error Trapping:
--------------
VB6:
===
Sub SomeSub
   On [Local] Error GoTo ErrorTrap
   ...some code...
   Exit Sub
ErrorTrap:
   ...optional code for error correction...
   Resume [optional: "Next" or line label]
End Sub

B4A:
===
Sub SomeSub
   Try
      ...some code...
   Catch [only executes if error above]
      Log(LastException) [optional]
      ...optional code for error correction...
   End Try
End Sub

WIth B4A, if you get an error caught in the middle of a large subroutine, you can
NOT make a correction and resume within the code you were executing. Only the code
in "Catch" gets executed. That would seem to make Try-Catch-End Try of use mainly
during development.

Try-Catch in place of GoTo:
--------------------------

Try-Catch can be used as a substitute for GoTo [line label] for forward, but not
backward, jumps. It cannot be used to replace GoSub.

Start the code with "Try" and replace the line label with "Catch".
Replace "GoTo [line label]" with code which will create an exception, which causes
a jump to "Catch", such as OpenInput("bad path", "bad filename").


How to sort a List:
------------------
I searched long and hard to find out how to sort a List and couldn't find it.
A message posted asking how to do it was not answered, so maybe NOBODY knows.
Anyway, here's the syntax:

listName.Sort(True)

That's it. Put it on a line by itself.


Events sub signatures:
---------------------
Each "View" ("control", in VB) has certain "events" it supports, such as a Click
event for a button, TextChanged event for an editText View, etc.

In VB6's code windows, you select a control in the left drop-down list and the
event in the right list.

In B4A, you start by typing "Sub viewName" followed by a space and follow the
prompts, pressing Enter after each selection until B4A ends with "EventName"
highlighted. This is where you would type in the name of the Sub.
 
Last edited:
Upvote 0

nfordbscndrd

Well-Known Member
Licensed User
Longtime User
Ironically, the last thing in the list in the preceding post gets us back to the subject of this thread -- a B4A equivalent to GoTo.

Try - Catch - End Try can be used to replace GoTo LineLabel, but only to jump forward.

VB6 code could look like this:

B4X:
Sub SomeSub(...)
      ...some code...
      If something Then GoTo SomePlace
      ...some more code...
SomePlace:
      ...code continues...
End Sub

In B4A, it can be done like this:

B4X:
Sub SomeSub(...)
     Try
          ...some code...
          If something Then OpenInput("badDirName, "badFileName")
          ...some more code...
     Catch 
          ...optionally, some code to execute before continuing...   
          ...optionally Return to exit sub...          
     End Try
     ...code continues...
End Sub

The GoTo LineLabel can be replaced with any piece of code which will cause an Exception, such as trying to open a non-existent file with the OpenInput command as shown above. This will cause the program to jump to Catch. In the code which continues, you could set up as many other jumps forward as you need using Try-Catch.

In VB6, GoTo can also jump back to a previous line, such as:

B4X:
Sub SomeSub(...)
     ...some code...
SomeLabel:
     ...code to jump back to continues...
     If whatever Then GoTo SomeLabel
     ...code continiues...

This cannot be done in B4A with Try-Catch.
 
Last edited:
Upvote 0

nfordbscndrd

Well-Known Member
Licensed User
Longtime User

I kept the example simple, but if you look back at the 500 lines of code I put in post #11, you will see, as I noted there, that it has 15 places where it says "GoTo AbortSave".

It is probably not even possible to work that code into an If-Then-Else block, but even if you could, it would take a LOT of work.

With the Try-Escape, all I have to do is start with "Try", replace the "AbortSave:" line label with "Catch", end with "End Try" -- all of which takes a few seconds, then replace every "GoTo AbortSave" with "OpenInput('bad', 'bad') -- a global replace that takes another few seconds.

Want to time it and see who beats?

I'm not saying that the Try-Catch kludge is ideal programming technique, but if you are trying to convert a bunch of VB6 code over, it is definitely the easiest way (IMHO).
 
Upvote 0

nfordbscndrd

Well-Known Member
Licensed User
Longtime User
The VB6-to-B4A list in post #21 has been updated with the following:

In the prior list, a B4A alternative to Mid$(text, n, x) was shown, but that is just for getting a string OUT of the text variable, such as s$ = Mid$(text, n, x). To convert Mid$(text, n, x) = text2 requires different B4A code.

In VB6, "n" is the position where the insertion starts and "x" is the maximum number of characters to insert.

"z" is the lesser of "x" and the length of "text2", which is the maximum amount of text in the original variable to overwrite --

In Example 1, x=3 and text2.Length=3, so a complete replacement is done.

In Example 2, x=3 and text2.Length=2, so only 2 characters in text are replaced.

In Example 3, x=1 and text2.Length=2, so only 1 character in text is replaced.​
B4X:
        VB6                        B4A
Mid$("abcde", 1, 1) = "a" = letter array index 0
Mid$("abcde", 2, 1) = "b" = letter array index 1
Mid$("abcde", 3, 1) = "c" = letter array index 2
Mid$("abcde", 4, 1) = "d" = letter array index 3
Mid$("abcde", 5, 1) = "e" = letter array index 4

VB6: 
Mid$(text, n, x) = text2

B4A:
text = text.SubString2(0, n-2) & _              
       text2.SubString2(0, x-1) & _             
       text.SubString(n-1 + z)  where...        
         z = Min(x, text2.length)               

Example 1: Mid$("abcde", 2, 3) = "jkl" = "ajkle"
         n=2, x=3, text="abcde", text2="jkl"    
       text.SubString2(0, n-2) = "a"            
       text2.SubString2(0, x-1) = "jk"          
         z = Min(x, text2.Length) = 3           
       text.SubString(n-1 + z) = "e"            
         = "ajkle"                              

Example 2: Mid$("abcde", 2, 3) = "jk" = "ajkde"
         n=2, x=3, text="abcde", text2="jk"     
       text.SubString2(0, n-2) = "a"            
       text2.SubString2(0, x-1) = "jk"          
         z = Min(x, text2.Length) = 2           
       text.SubString(n-1 + z) = "de"           
         = "ajkde"                              

Example 3: Mid$("abcde", 3, 1) = "jk" = "abjde" 
         n=3, x=1, text="abcde", text2="jk"     
       text.SubString2(0, n-2) = "ab"           
       text2.SubString2(0, x-1) = "j"           
         z = Min(x, text2.Length) = 1           
       text.SubString(n-1 + z) = "de"           
         = "abjde"
 
Last edited:
Upvote 0

thecrowkaka

Member
Licensed User
Longtime User
Thanks all for this excellent guide. Indeed useful for a VB6 programmer like myself.

However a few points that i need input.

1. In vb6, you have a Preserve keyword to be used along with Redim used for increasing the elements in an array without discarding the existing data. What is the B4PPC equivalent?

2. I am used to creating classes in vb6.

Public Property Get property() As Integer
property = propvariable
End Property

Public Property Let property(value As Integer)
propvariable= value
End Property

This is something i commonly use in vb6. I happen to use a lot of classes.
ANything of that sort that I can do in B4PPC.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
1. In vb6, you have a Preserve keyword to be used along with Redim used for increasing the elements in an array without discarding the existing data. What is the B4PPC equivalent?
You should use a List instead of an array. It allows you to add and remove items and it also has other powerful features.

2. I am used to creating classes in vb6.
There are no classes in B4A. You can use Type to declare your own structures.
 
Upvote 0

FrankR

Member
Licensed User
Longtime User
Let me throw in two cents - you don't want a GoTo.
You always want to find another way.

:sign0089:
 
Upvote 0

nfordbscndrd

Well-Known Member
Licensed User
Longtime User
Let me throw in two cents - you don't want a GoTo.
You always want to find another way.

In my 35+ years of programming, I have often been faced with a choice of spending a lot of time rewriting code to avoid a GoTo, or simply using a GoTo and getting on with the project. I've never experienced any negative impact from using the GoTo. Sometimes practicality has to take the place of what they told you in Programming 101.
 
Upvote 0

FrankR

Member
Licensed User
Longtime User

I hear you. And, I reach for the practical solution all the time. But, in my 25+ years of experience, I have:
- Never had to use a GoTo
- Suffered greatly from inheriting code of others that Did
 
Upvote 0

nfordbscndrd

Well-Known Member
Licensed User
Longtime User
I hear you. And, I reach for the practical solution all the time. But, in my 25+ years of experience, I have:
- Never had to use a GoTo
- Suffered greatly from inheriting code of others that Did

If you have never used GOTO, then either you have never had to modify a complex sub to get out of a heavily nested spot, or you wasted a lot of time rewriting it simply to avoid a perfectly legitimate command. (After all, it's not like we hacked VB to get GOTO into it.)

Anything can be misused, including GOTO, but I don't see why GOTO should be any harder to follow (when used properly) than GOSUB or SUB or FUNCTION or ON ERROR (with its different RESUMEs) or EXIT SUB/DO/FOR or TRY or any other commands which jump out of the current line of code. (See the code I posted in msg.#11 of this thread and tell me you can't follow the GOTO's in it. Yes, I could have repeated those exit lines of codes every place I used GOTO, but that's really putting form over function when the GOTO code is extremely easy to follow.)

There are other things that make code harder to follow than using GOTO. For example, in B4A, is TopNum(n) a variable or a call to a Sub? Is it an integer or a string? Is it a local variable or a Global? Much more confusing than a GOTO, and much more easily avoided by using variable type prefixes on Global variables (e.g.: strSomeStringVar), DIM-ing all local variables, etc.
 
Last edited:
Upvote 0

agraham

Expert
Licensed User
Longtime User
In my 45 years of hardware design, programming and project management, including running a couple of teams writing the OS and GUI software for early Hitachi SH based PDAs, I would never contenance the use of a GOTO for professionally written software for release to a customer. Block structured languages were designed for a purpose and GOTO subverts that. Any of member of my teams that resorted to such a cludge, and unfortunately it does exist in C, would have been immediately told what to do with it.

At least Kernighan and Ritchie had the grace in to admit that in the classic book "The C Programming Language" -

"C provides the infinitely-abusable goto statement, and labels to branch to it. Formally the goto is never necessary, and in practice it is almost always easy to write code without it. We have not used goto in this book." Amen!
 
Upvote 0

nfordbscndrd

Well-Known Member
Licensed User
Longtime User
... I would never contenance the use of a GOTO for professionally written software...

I showed an example of a reasonable use of GOTO and listed several other programming features which are at least as obfuscating and often more so, and your reasoned response is "I would never countenance it"?? Oh, okay then. I certainly can't argue with that. You must be right.
 
Upvote 0

lorebf

Member
Licensed User
Longtime User
I really don't understand why some ppl hate "goto" so much...
Sure... you can write a program without it... but why stop there?.. there is a LOT of commands that you wouldn't need because you can do it anyway without them..
 
Upvote 0

kblood

New Member
Hmmm... goto. I miss that simple command from the C64, and I used it in VB as well of course. In PHP there were several ways to replace the goto command, making functions and such.

Seems the only real way to do it in this script would be to hack up the code, and make it into if settings in some kind of a loop function. Then making the IF sentences see what your "goto" variable is set to. But the really annoying part is you would probably need two goto variables, one for where to goto, but also one for where it should goto after doing that. Or at least some other script that it should always go through in this loop.

I am pretty sure it is possible to do, the annoying part will be doing this for each different goto you used in this script. I am thinking, maybe it is possible to make a converter that can figure out how to make goto into if-then checks instead. But will probably take longer to figure that out than it would be to turn the script into chunks of goto parts of the script. If there is no gosub, then a gosub shoudl probably just be require two goto variables. One that makes it go there, and one for where it should return to.

But other than that it would require almost starting from scratch I guess and rethinking the structure even more than that. I am a bit surprised that this code does not have go functions or anything like that.

Goto like stuff still exists in new code, it just have new names and requires some very different programming to make it work. I did like the functions way of doing them though in PHP.
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…