【问题标题】:VBA Excel, loop through variablesVBA Excel,循环变量
【发布时间】:2014-04-22 17:42:34
【问题描述】:

现在尝试修复以下几个小时,我想我只是永久地坚持下去。言归正传。

当前代码:

Sub ttttt()
Dim i1 As Integer, i2 As Integer, i3 As Integer, i4 As Integer
Dim vGen As Variant
Dim vCurrent As Variant

i1 = 1
i2 = 20
i3 = 300
i4 = 4000

vGen = Array(i1, i2, i3, i4)

For Each vCurrent In vGen
    MsgBox vCurrent
Next

End Sub

问题 1 我希望能够以与返回类型相同的方式返回变量名称:TypeName()。所以对于第一个循环,msgbox 会说:i1 等等。我正在尝试 .name 等的不同组合,但似乎总是让我失望。

问题 2 问题 1 的原因是,下一步我想根据变量名称在原始值中添加一些内容。

希望我想要这样的东西(显然这段代码不起作用,它只是为了演示):

For Each vCurrent In vGen
    vCurrent.name = vcurrent + iSomeNumber
Next

iSomeNumber 将从程序的另一部分传入,然后我可以稍后检索更新的单个变量(即 i1 将不再是值 1,而是 1 + iSomeNumber)。

希望我已经清楚地解释了我的问题,如果您需要任何其他信息,请告诉我。

另外我还要AFK 4小时,所以我的回复可能会有点延迟。

提前感谢您的帮助!

【问题讨论】:

    标签: excel vba loops


    【解决方案1】:

    您可以查看Scripting.Dictionary 对象:它允许您将值与字符串“keys”相关联

    Dim d, k
    
    Set d = CreateObject("Scripting.Dictionary")
    
    d.Add "A", 10
    d.Add "B", 20
    d.Add "C", 30
    
    For Each k in d
        Debug.print k, d(k)
    Next k
    
    d("B") = d("B") + 100
    

    【讨论】:

    • 谢谢蒂姆,非常巧妙的方法! :)
    【解决方案2】:

    蒂姆·W 好主意。

    稍作修改。尝试运行这个:

    Sub ttttt()
    
    Set Dict = CreateObject("Scripting.Dictionary")
    
    Dict.Add "A1", 10
    Dict.Add "B1", 20
    Dict.Add "B2", 30
    Dict.Add "C1", 40
    
    ADDValue1 = 50
    ADDValue2 = 100
    ADDValue3 = 150
    
    For Each k In Dict
    
    If k Like ("*A*") Then
    Debug.Print Dict(k) + ADDValue1
    End If
    
    If k Like ("*B*") Then
    Debug.Print Dict(k) + ADDValue2
    End If
    
    If k Like ("*C*") Then
    Debug.Print Dict(k) + ADDValue3
    End If
    
    Next k
    
    End sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-17
      • 2015-04-12
      • 2019-02-11
      • 2017-05-26
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多