VBA程序为具有值的所有单元格着色

时间:2015-08-07 13:59:01

标签: excel vba

我刚开始自学VBA,所以提前谢谢。为什么这会给我一个错误?代码搜索将来的日期列。然后在该列中搜索具有值并将其颜色为黄色的任何单元格。

谢谢!

    Sub Macro1()
     Dim cell As Range
     Dim cell2 As Range
     Dim ColumnN As Long



For Each cell In Range("I2:ZZ2")

    If cell.Value > Now() Then

    '

    ColumnN = cell.Column
    ColumnL = ConvertToLetter(ColumnN)
    MsgBox ColumnL & cell.Row

        For Each cell2 In Range("ColumnL:ColumnL")

            If Not cell2 Is Empty Then



                cell2.Interior.ColorIndex = 6

            End If

        Next cell2
    End If
   End Sub()





    Function ConvertToLetter(lngCol As Long) As String
    Dim vArr
    vArr = Split(Cells(1, lngCol).Address(True, False), "$")
    ConvertToLetter = vArr(0)
    End Function

2 个答案:

答案 0 :(得分:0)

要检查单元格是否为空,您需要切换完成单元格的顺序。将您的If Not语句切换为If Not IsEmpty(cell2) Then

此外,强烈建议不要将变量命名为cell,因为这是一些特殊字词" (我忘了技术术语)Excel使用。我总是只使用cel

Sub test()
Dim cel     As Range
Dim cel2    As Range
Dim ColumnN As Long

For Each cel In Range("I2:ZZ2")

    If cel.Value > Now() Then

        ColumnN = cel.Column
        ' ColumnL = ConvertToLetter(ColumnN)
        ' MsgBox ColumnL & cell.Row
        If Not IsEmpty(cel) Then
            cel.Interior.ColorIndex = 6
        End If
    End If
Next cel

End Sub

编辑:如果您注意到,我还调整了您的cell2 range。这消除了运行另一个宏的需要(有时可能是问题的原因),因此您只需要列号。

Edit2:我删除了" ColumnL"范围选择 - 这是为了什么?我可以将其重新添加,但不确定为什么你要循环通过I:ZZ列,但只在N列中突出显示。

EDIT2:

我调整了代码,现在它的速度要短得多,应该运行得更快:

Sub Macro2()

Dim cel As Range, rng As Range
Dim lastCol As Long

Application.ScreenUpdating = False

lastCol = Cells(2, 9).End(xlToRight).Column ' Note, this assumes there are NO gaps in the columns from I:ZZ
'lastCol = cells(2,16384).End(xltoleft).column ' use this instead, if there are gaps in I2:ZZ2

Set rng = Range(Cells(2, 9), Cells(2, lastCol))

For Each cel In rng

    If cel.Value > Now() Then
        cel.Interior.ColorIndex = 6
    End If
Next cel
Application.ScreenUpdating = True
End Sub

答案 1 :(得分:0)

你快到了! 要解决两个主要问题:

取代:

For Each cell2 In Range("ColumnL:ColumnL")

For Each cell2 In Range(ColumnL & ":" & ColumnL)

If Not cell2 Is Empty Then

If Not IsEmpty(cell2) Then

这应该导致以下结果:

Sub Macro1()

Dim cell As Range
Dim cell2 As Range
Dim ColumnN As Long
Dim ColumnL As String


For Each cell In Range("I2:ZZ2")

    If cell.Value > Now() Then

        ColumnN = cell.Column
        ColumnL = ConvertToLetter(ColumnN)
        MsgBox ColumnL & cell.Row

        For Each cell2 In Range(ColumnL & ":" & ColumnL)

            If Not IsEmpty(cell2) Then



                cell2.Interior.ColorIndex = 6

            End If

        Next cell2

    End If
Next cell

End Sub


    Function ConvertToLetter(lngCol As Long) As String
    Dim vArr
    vArr = Split(Cells(1, lngCol).Address(True, False), "$")
    ConvertToLetter = vArr(0)
    End Function

虽然效率有点低,但它还是完成了工作!

相关问题