使用tabArray时如何跳过单元格?

时间:2019-06-20 18:00:50

标签: arrays excel vba

我在工作表上使用的tabArray将会循环遍历单元格F13,F17等,直到F31(所有奇数编号的单元格)。每个单元格都是一个下拉菜单,供用户进行选择。如果数组中的单元格具有灰色的背景,我希望它跳到数组中的下一个单元格。例如,F21具有灰色背景,但是,如果我在F13中进行选择,它将移动到的下一个单元格是F23。我在单元格F21之前进行选择更改的每个单元格都将自动移动到F23。

我尝试“退出”和“转到”没有成功。

tabArray = Array  ("F13","F15","F17","F19","F21","F23","F25")

For I = LBound(tabArray) to UBound (tabArray) 
      If tabArray(I) = target.address(0,0) then 
       If I = UBound(tabArray) then 
       Me.Range(tabArray(LBound(tabArray))).Activate 

      Else  
      Me.Range(tabArray(I+1)).Activate

      end if 
  ElseIf Range(tabArray(I)).Interior.Colorindex = 15 then 
      If I = UBound(tabArray) then 
      Me.Range(tabArray(LBound(tabArray))).Activate 

     Else  
     Me.Range(tabArray(I+1)).Activate

     end if 
   end if 
Next I 

如果F23的单元格背景为灰色,并且我在F13中进行了选择,我希望它移动到的下一个单元格是F15,但是实际输出是它移到了F25单元格。

1 个答案:

答案 0 :(得分:1)

您必须小心如何跳过使用tabArray的过程。下面的示例显示了一种实现方法。

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim tabArray As Variant
    tabArray = Array("F13", "F15", "F17", "F19", "F21", "F23", "F25")

    Dim i As Long
    Dim j As Long
    Dim nextHighlightCell As Long
    For i = LBound(tabArray) To UBound(tabArray)
        If tabArray(i) = Target.Address(0, 0) Then
            '--- a cell has changed within our tab list, so now find
            '    the next cell in the array that is not highlighted

            '--- increment to the next array position or wrap around
            If i = UBound(tabArray) Then
                j = LBound(tabArray)
            Else
                j = i + 1
            End If

            nextHighlightCell = -1
            Do While Not j = i
                If Range(tabArray(j)).Interior.ColorIndex = 15 Then
                    '--- this one is gray, so skip it
                    If j = UBound(tabArray) Then
                        j = LBound(tabArray)
                    Else
                        j = j + 1
                    End If
                Else
                    nextHighlightCell = j
                    Exit Do
                End If
            Loop

            '--- skip to the next indicated cell
            If Not nextHighlightCell = -1 Then
                Range(tabArray(nextHighlightCell)).Activate
                Exit For
            End If
        End If
    Next i
End Sub
相关问题