Excel VBA - 工作表选择问题

时间:2015-12-29 09:31:52

标签: excel vba excel-vba

您可以在下面找到我的代码。这是非常基本的,但问题也是如此:) 因此,我需要根据工作表DATABASE(x,y,z)中的值对工作表CALENDAR中的单元格进行着色。

但是,此代码颜色正确的单元格,但在表DATABASE而不是CALENDAR。 正如您所看到的,我尝试激活并选择表格CALENDAR进出for循环,但它仍然无法正常工作。

请帮助!

提前结束"!

Sub calendar_fill()

Worksheets("DATABASE").Activate
Set sh = ThisWorkbook.Sheets("DATABASE")
Dim i As Long
Dim x As Long
Dim y As Long
Dim z As Long
Dim dummy As Long

i = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count

Sheets("CALENDAR").Select
Worksheets("CALENDAR").Activate

For j = 1 To i - 2

    x = Worksheets("DATABASE").Cells(2 + j, "S").Value
    y = Worksheets("DATABASE").Cells(2 + j, "T").Value
    z = Worksheets("DATABASE").Cells(2 + j, "U").Value

    dummy = Worksheets("CALENDAR").Cells(1, 1).Value
    Sheets("CALENDAR").Select
    Worksheets("CALENDAR").Activate

    'annoucement
    Range(Cells(j + 5, x + 3), Cells(j + 5, y - 1 + 3)).Interior.Color = 6750207

    'open
    Range(Cells(j + 5, y + 3), Cells(j + 5, z + 3)).Interior.Color = 5296274


Next j

End Sub

2 个答案:

答案 0 :(得分:2)

您不需要选择或激活 - 只需使用工作表对象限定RangeCells次来电:

Sub calendar_fill()
    Dim i                     As Long
    Dim x                     As Long
    Dim y                     As Long
    Dim z                     As Long
    Dim dummy                 As Long
    Dim sh                    As Worksheet
    Dim shCal                 As Worksheet

    Set sh = ThisWorkbook.Sheets("DATABASE")
    Set shCal = ThisWorkbook.Sheets("CALENDAR")

    i = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count


    For j = 1 To i - 2

        x = sh.Cells(2 + j, "S").Value
        y = sh.Cells(2 + j, "T").Value
        z = sh.Cells(2 + j, "U").Value

        With shCal
            dummy = .Cells(1, 1).Value

            'annoucement
            .Range(.Cells(j + 5, x + 3), .Cells(j + 5, y - 1 + 3)).Interior.Color = 6750207

            'open
            .Range(.Cells(j + 5, y + 3), .Cells(j + 5, z + 3)).Interior.Color = 5296274
        End With


    Next j

End Sub

答案 1 :(得分:0)

尝试

  

sh.Range(Cells(j + 5,x + 3),Cells(j + 5,y - 1 + 3))。Interior.Color   = 6750207

我认为没有必要激活您的工作表或范围,因为您的工作表已经设置。