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

Time:11-03

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

CodePudding user response:

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

CodePudding user response:

A MsgBox in a For...Next Loop

Option Explicit

Sub OutputTxt()
    Const ProcTitle As String = "Output Text"
    
    Const MsgLeft As String = "Txt : "
    Const MsgMiddle As String = "Test "
    Const Chr0 As Long = 64 ' '65' is 'A', '90' is 'Z'
    Const TotalCount As Long = 8 ' '8' is 'H', max is '26' is 'Z'
    
    Dim Counter As Long
    Dim Msg As String
    Dim MsgRight As String
    
    For Counter = 1 To TotalCount
        MsgRight = ChrW(Chr0   Counter)
        Msg = MsgLeft & MsgMiddle & MsgRight
        MsgBox Msg, vbInformation, ProcTitle
    Next Counter

End Sub

Sub OutputTxtShort()
    
    Const TotalCount As Long = 8 ' '8' is 'H', max is '26' is 'Z'
    
    Dim Counter As Long
    
    For Counter = 1 To TotalCount
        MsgBox "Txt : Test " & ChrW(64   Counter)
    Next Counter

End Sub
  • Related