VBA循环根据标准

时间:2015-07-22 15:51:49

标签: excel vba excel-vba

我目前正在尝试实现一个宏,它通过D列循环并根据其值,我希望它在值存在的特定行上的某些多个单元格中着色。这需要在满足特定条件的每一行发生,但我只能在选择活动单元而非自动化过程时才能使其工作。以下是我到目前为止的情况:

Sub Validate()

Dim rng As Range
Dim row As Range
Dim cell As Range

Set rng = Range("D4:D1000")

For Each cell In rng
    If cell.Value = "Building Blocks" Then
        ActiveCell.Offset(, 16).Interior.ColorIndex = 7

    ElseIf cell.Value = "Test" Then
        cell.Interior.ColorIndex = 4

    End If
Next
End Sub

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:1)

您正在引用以下行中的ActiveCell ...

ActiveCell.Offset(, 16).Interior.ColorIndex = 7

你真正想要的是......

cell.Offset(, 16).Interior.ColorIndex =7

答案 1 :(得分:1)

我不想为你重写你的代码,所以我只是对你的代码进行了一些修改:

Sub Validate()

Dim rng As Range
Dim row As Range
Dim cell As Range
Dim counter As Long

Set rng = Range("D4:D1000")
Range("D4").Select

For Each cell In rng


If cell.Value = "Building Blocks" Then
    ActiveCell.Offset(counter, 16).Interior.ColorIndex = 7



ElseIf cell.Value = "Test" Then
    ActiveCell.Offset(counter, 16).Interior.ColorIndex = 4


End If
counter = counter + 1

Next
End Sub

如3-14159265358979323846所述,更好的方法是将您的原始代码更改为将Cellcell更改为Cell:

Sub Validate()

Dim rng As Range
Dim row As Range
Dim cell As Range


Set rng = Range("D4:D1000")


For Each cell In rng


If cell.Value = "Building Blocks" Then
    cell.Offset(, 16).Interior.ColorIndex = 7



ElseIf cell.Value = "Test" Then
    cell.Offset(, 16).Interior.ColorIndex = 4


End If


Next
End Sub

答案 2 :(得分:0)

不确定我理解。这将通过D列,如果找到Building Blocks,它将在该行中查找第二个Building Block。如果它找到它,它将在colorindex 7中为单元格着色。与find相同的想法。未经测试。

Sub Validate()

Dim rng As Range
Dim row As Range
Dim cell As Range

Set rng = Range("D4:D1000")


For Each cell In rng


If cell.Value = "Building Blocks" Then
    for i = 2 to 50 'Howverlong your row is, could go to the end too if dynamic
        if cell(,i).value = cell.value then cell(,i).Interior.ColorIndex = 7
    next



ElseIf cell.Value = "Test" Then
    for i = 2 to 50 'Howverlong your row is, could go to the end too if dynamic
        if cell(,i).value = cell.value then cell(,i).Interior.ColorIndex = 4        
    next


End If

Next
End Sub