gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:09:12 24 4
gpt4 key购买 nike

我编写了代码以在消息框中显示字符串中的文本 (st1, st2, st3, ...)随着它在 For 循环中前进,但它只显示为数字。

我希望下面的代码在其第一个 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

关于excel - 如何让字符串显示在具有for循环的消息框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69820899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com