从左右,上下,上下,左右更改搜索流程

时间:2016-09-15 11:09:32

标签: excel-vba vba excel

我希望它从头到尾开始搜索第一列,然后是第二列,依此类推。

在“for each”部分,我想更改流程

Private Sub CommandButton1_Click()
    Dim i As Integer
    Dim j As Integer

    For j = 2 To 2
        For i = 21 To 21

            If Cells(i, j).Value > 0 Then
                Cells(i, j).Value = Cells(i, j).Value - 1
                Cells(i, j).Offset(0, -1).Select
            End If

            'that is the Matrix I want to Change the search flow in'
            For Each cell In Range("a2:aap15")

                If cell.Interior.ColorIndex = 6 Then
                    If cell.Value = "" Then

                        cell.Value = ActiveCell.Value
                        Exit For

                    End If
                End If

            Next    
        Next    
    Next

End Sub

我必须写这句话,因为stackoverlow不允许我发帖,直到它认为我不再拥有大部分代码。

新建议(仍然是同一个问题):

Private Sub CommandButton1_Click()
Dim i As Integer
Dim j As Integer

'NEW'
Dim cell As Range, column As Range

For j = 2 To 2
For i = 21 To 21

If Cells(i - 1, j).Value = 0 Then
If Cells(i, j).Value > 0 Then
Cells(i, j).Value = Cells(i, j).Value - 1
Cells(i, j).Offset(0, -1).Select
End If
End If


'NEW'
For Each column In Range("a2:aap15").Columns
    For Each cell In column.Cells


If cell.Interior.ColorIndex = 6 Then
If cell.Value = "" Then

cell.Value = ActiveCell.Value

Exit For

End If
End If

Next
Next   
Next
next

End Sub

how it shold be

how it is

2 个答案:

答案 0 :(得分:0)

您可以通过迭代范围列的单元格来实现此目的。

Dim cell As Range, column As Range

For Each column In Range("a2:aap15").Columns
    For Each cell In column.Cells

        If cell.Interior.ColorIndex = 6 Then
            If cell.Value = "" Then

                cell.Value = ActiveCell.Value
                Exit For

            End If
        End If
    Next
Next

答案 1 :(得分:0)

以下内容取决于AutoFilter method。 .AutoFilter需要一个标题'处理中未包含但行1的行不能完全为空。

Option Explicit

Sub firstBlankYellows()
    Dim c As Long, str As String

    str = "Task 1"
    With Worksheets("Sheet4")
        If .AutoFilterMode Then .AutoFilterMode = False
        With .Range("A1:AP15")
            For c = 1 To .Columns.Count
                With .Columns(c)
                    .AutoFilter field:=1, Criteria1:=RGB(255, 255, 0), Operator:=xlFilterCellColor
                    With .Resize(.Rows.Count - 1, 1).Offset(1, 0)
                        If Not Intersect(.SpecialCells(xlCellTypeVisible), _
                                         .SpecialCells(xlCellTypeBlanks)) Is Nothing Then
                            Intersect(.SpecialCells(xlCellTypeVisible), _
                                      .SpecialCells(xlCellTypeBlanks))(1) = str
                            Exit For
                        End If
                    End With
                    .AutoFilter
                End With
            Next c
        End With
        If .AutoFilterMode Then .AutoFilterMode = False
    End With
End Sub

enter image description here