如何让字符串显示在具有for循环的消息框中

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

我编写了代码以在消息框中显示字符串中的文本(st1st2st3、...) 14=] 循环,但它只显示为数字。

我希望波纹管代码在其第一个 For 循环中输出 txt : Test A。但它给了我 txt : 1。所以在整个循环中它只会显示循环编号而不是字符串中的文本。请帮忙。

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

每当你觉得需要在变量名中使用数字时:你做错了什么!请改用数组。

您不能遍历名为 st1st8 的变量,但您可以遍历数组:

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

For...Next 循环中的 MsgBox

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