Search code examples
excelvbamessagebox

How to get the Strings to show in message box which has for loop


I wrote the code to appear the texts in the string (st1, st2, st3, ...) in a message box as it progress through the For loop but it only appear as numbers.

I want the bellow code to output txt : Test A in its 1st For loop. but instead it gives me txt : 1. So through out the loop it will only show the loop number not the text in the string. Please help.

Sub OutputTxt()
    'States of the prosessing----------------------------
    Dim stat As String

    'string values - Discriptions
    Dim st1 As String
    Dim st2 As String
    Dim st3 As String
    Dim st4 As String
    Dim st5 As String
    Dim st6 As String
    Dim st7 As String
    Dim st8 As String

    st1 = "Test A"
    st2 = "Test B"
    st3 = "Test C"
    st4 = "Test D"
    st5 = "Test E"
    st6 = "Test F"
    st7 = "Test G"
    st8 = "Test H"

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

    Dim Counter As Long
    Dim TotalCount As Long

    'Initialize the Variables and Objects
    TotalCount = 8

    For Counter = 1 To TotalCount
        stat = st & Counter
                        
        'Update the msg box
        MsgBox ("Txt : " & stat)               
    Next Counter
End Sub

Solution

  • Whenever you have the feeling you need to use numbers in variable names: You are doing something wrong! Use arrays instead.

    You cannot loop through variables named like st1 to st8 but you can loop through an array:

    Option Explicit 
    
    Public Sub OutputTxt()
        'string values - Discriptions
        Dim st(1 to 8) As String
        st(1) = "Test A"
        st(2) = "Test B"
        st(3) = "Test C"
        st(4) = "Test D"
        st(5) = "Test E"
        st(6) = "Test F"
        st(7) = "Test G"
        st(8) = "Test H"   
    
        Dim Counter As Long
        For Counter = LBound(st) To UBound(st) 'loop through entire array                        
            'Update the msg box
            MsgBox ("Txt : " & st(Counter))               
        Next Counter
    End Sub