当其他值存在时,VBA会突出显示单元格

时间:2017-10-18 16:47:17

标签: excel vba excel-vba

我希望在不同列中输入值时突出显示电子表格中的某些单元格。我意识到这可以通过条件格式化来完成,但是由于公司内部的情况,我必须使用VBA。 (电子表格将传递到另一个无法读取条件格式的程序)

每当 ANYTHING 输入L列时,我试图在我的值范围内突出显示11个不同的列。例如,当它输入L2中的日期时,则C2,J2,K2等突出显示为黄色。

以下是我的想法..不幸的是,当我运行宏时,没有任何反应。我看到它运行,但我没有得到任何结果 - 甚至没有错误信息。提前感谢你帮助我的时间!

Dim rng As Range, r As Range

Set wb = ThisWorkbook
Set sht1 = wb.Sheets("From GIS")
Set sht2 = wb.Sheets("To MapCall")

Set rng = Intersect(sht2.UsedRange, Range("L:L")).Cells


For Each r In rng
    If r.Value = "" Then
        Cells(r.Row + 1, "C,J,K,Q,AI,AV,AW,AX,AY,AZ,BR").Interior.Color = RGB(255, 255, 0)

    End If
Next r

2 个答案:

答案 0 :(得分:1)

请试一试并更改r.Value =""到r.Value<> ""如果要在范围内输入某些颜色而不是空白时要应用颜色。根据您的实际需要调整它。我也不确定你为什么用r.Row + 1?这不是你想要的,用i = r.Row替换下面代码中的i = r.Row + 1.

同样,声明代码中使用的所有变量也是一种很好的做法。

Dim wb As Workbook
Dim sht1 As Worksheet, sht2 As Worksheet
Dim rng As Range, r As Range, clrRng As Range
Dim i As Long
Set wb = ThisWorkbook
Set sht1 = wb.Sheets("From GIS")
Set sht2 = wb.Sheets("To MapCall")

Set rng = Intersect(sht2.UsedRange, Range("L:L")).Cells
For Each r In rng
    If r.Value = "" Then
        i = r.Row + 1
        Set clrRng = Union(Range("C" & i), Range("J" & i & ":K" & i), Range("Q" & i), Range("AI" & i), Range("AV" & i & ":AZ" & i), Range("BR" & i))
        clrRng.Interior.Color = RGB(255, 255, 0)
    End If
Next r

答案 1 :(得分:0)

一种方法是create a union of ranges

Sub test()

    Dim Rng As Range, r As Range, uRng As Range, row As Long

    Set wb = ThisWorkbook
    Set sht1 = wb.Sheets("From GIS")
    Set sht2 = wb.Sheets("To MapCall")

    Set Rng = Intersect(sht2.UsedRange, Range("L:L")).Cells

    For Each r In Rng
        If r.Value <> "" Then
            row = r.row

            Set uRng = Union(Cells(row, "C"), Cells(row, "J"))  'Etc... Keep going with each column
            uRng.Interior.Color = RGB(255, 255, 0)

        End If
    Next r

End Sub