对于带有标签和变量的每个循环

时间:2016-08-22 14:15:46

标签: excel-vba vba excel

我很难实现用户形式我有几个名为" l_MBout"," l_MBin"," l_Fin"还有很多。标题的值存储在名为" MBout"," MBin"," LFin"等等(这些是计算的整数 - 总是像相应的标签一样命名但没有" l _")。我的想法是为标签

定义一个数组
Public labelarray As Variant
labelarray = Array("l_MBin", "l_MBout", "l_Gin", "l_Gout", "l_Fin", "l_Fout", "l_DLZMB", "l_DLZG", "l_DLZF")

并使用类似的东西将变量中的值写入标签(删除前面" l _")

Public lbl As Variant

For Each lbl In labelarray
    If Right(lbl, Len(lbl) - 2) > 0 Then
        Managementsitzung.Controls(lbl & i1).Caption = Right(lbl, Len(lbl) - 2)
    Else
        Managementsitzung.Controls(lbl & i1).Caption = "-"
    End If
Next lbl

但似乎是

Right(lbl, Len(lbl) - 2)

没有链接到变量(我的猜测它仍然是一个字符串)

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:1)

你是对的。所有Right(lbl, Len(lbl) - 2)都是字符串,而不是变量。我可以建议制作两个并行数组,这样你就可以同时保存标签和变量。

labelarray = Array("l_MBin", "l_MBout", "l_Gin", "l_Gout", "l_Fin", "l_Fout", ...
valarray = Array(Mbin, MBout, Gin, Gout, Fin, Fout, ...

然后你可以遍历标签,但要检查值。

For i=lbound(labelarray) to ubound(labelarray)
    If valarray(i) > 0 Then
        Managementsitzung.Controls(labelarray(i) & i1).Caption = valarray(i)     
    Else
        Managementsitzung.Controls(labelarray(i) & i1).Caption = "-"
    End If
Next i

答案 1 :(得分:0)

将标签 objects 放在数组中,而不是它们的名称:

Option Explicit
Private labelarray As Variant

Private Sub UserForm_Initialize()
    labelarray = Array(l_MBin, l_MBout, l_Gin, l_Gout, l_Fin, l_Fout, l_DLZMB, l_DLZG, l_DLZF)
End Sub

然后您可以在循环中访问它们的属性:

Dim lbl As Variant

For Each lbl In labelarray
    With lbl
        If Right(.Name, Len(.Name) - 2) > 0 Then
            .Caption = Right(.Name, Len(.Name) - 2)
        Else
            .Caption = "-"
        End If
    End With
Next