代码之家  ›  专栏  ›  技术社区  ›  xhamsterIT

循环VBA Microsoft Excel

  •  0
  • xhamsterIT  · 技术社区  · 11 月前
    Private Sub UserForm_Activate()
    If ActiveSheet.Range("AK4").Value = 0 Then
        CXBTN1.Value = False
    ElseIf ActiveSheet.Range("AK4").Value = "FALSE" Then
        CXBTN1.Value = False
    Else
        CXBTN1.Value = True
    End If
    
    'CheckBox
    If ActiveSheet.Range("AL4").Value = 0 Then
        CXBTN2.Value = False
    ElseIf ActiveSheet.Range("AL4").Value = "FALSE" Then
        CXBTN2.Value = False
    Else
        CXBTN2.Value = True
    End If
    End Sub
    

    有什么方法可以让我绕过这个吗?我是手工做的。我似乎找不到这个循环。

    1 回复  |  直到 11 月前
        1
  •  0
  •   Torben Klein    11 月前

    这样地:

    celladdrs = Array("AK4", "AL4") 'extend as needed
    ctls= Array(CXBTN1, CXBTN2)
    for i = 0 to 1
        addr = celladdrs(i)
        ' Use "Set" for object assignment!
        Set control = ctls(i)
        If ActiveSheet.Range(addr).Value = 0 Then
            control.Value = False
        ElseIf ActiveSheet.Range(addr).Value = "FALSE" Then
            control.Value = False
        Else
            control.Value = True
        End If
    Next
    
        2
  •  0
  •   FaneDuru    11 月前

    假设所有要更改的按钮的名称都从1连续递增到85,请使用下一种方式。不需要在数组中放置任何东西。如果你添加一个新按钮,只需更改要递增的最大数字(85到86,依此类推……):

    Private Sub UserForm_Activate()
      Dim i As Long, rngMatch As Range
      Const btPref As String = "CXBTN"
      Set rngMatch = Range("AK4")
      For i = 1 To 85 'use here the number of buttons
        If rngMatch.Offset(, i - 1).Value = 0 Or rngMatch.Offset(, i - 1).Value = "FALSE" Then
            Me.Controls(btPref & i).Value = False
        Else
            Me.Controls(btPref & i).Value = True
        End If
      Next i
    End Sub
    

    未经测试,但它应该按需工作。当然,如果针对列增量的按钮命名遵守规则。。。