首页 > 解决方案 > 基于颜色和值获取 - 编译但没有输出

问题描述

我正在处理一个动态工作表,其中内容的总行数和列数将发生变化。

我尝试做的是,使一个活动单元格通过工作表。它从包含内容的最后一列开始(我UsedRange在这里使用),从第 7 行到最后一行不为空白。

当 1) 活动单元格具有索引 16 或 36 的颜色填充;2)活动单元格没有值,该单元格将获取存储在匹配行E中的值。

当击中 E 列时,循环将结束(我还没有走那么远)。

我将在下面附上我的代码以获得所有可能的帮助,因为它符合但不返回任何结果......再次感谢您!

Sub catchCurrentAutomated()

    Dim column As Integer
    Dim row As Integer
    Dim Cell As Range

    row = 7
    column = ActiveSheet.UsedRange.Columns.Count
    Set Cell = ActiveCell

      While range("A" & row) <> ""

        If Cell.Interior.ColorIndex = 16 And _
           IsEmpty(Cell.Value) = True Then

        Cell.Value = Cells(ActiveCell.row, "E").Value

        ElseIf Cell.Interior.ColorIndex = 36 And _
           IsEmpty(Cell.Value) = True Then

        Cell.Value = Cells(ActiveCell.row, "E").Value

        End If

        row = row + 1
        column = column - 1

      Wend

End Sub

标签: excelvbawhile-loop

解决方案


像这样的东西应该可以工作(未经测试)

Sub catchCurrentAutomated()

    Dim col As Long '<< use Long not Integer
    Dim row As Long
    Dim c As Range, ws As Worksheet, lr As Long, indx

    Set ws = ActiveSheet
    col = ws.UsedRange.Columns.Count
    lr = ws.Cells(Rows.Count, 1).End(xlUp).row  'last occupied cell in ColA
    
    Do While col > 5
        For row = 7 To lr
            With ws.Cells(row, col)
                indx = .Interior.Color.Index
                If (indx = 16 Or indx = 36) And Len(.Value) = 0 Then
                    .Value = ws.Cells(row, "E").Value
                End If
            End With
        Next row
        col = col - 1 'next column to left
    Loop

End Sub

推荐阅读