Excel VBA – 问题与工作表select

下面你可以find我的代码。 这是非常基本的,但问题也是如此:)所以,我需要根据表DATABASE(x,y,z)中的值为工作表CALENDAR上的单元格着色。

但是,这段代码会校正单元格的颜色,但在DATABASE表格中,而不是CALENDAR。 正如你所看到的,我尝试激活并select表CALENDAR进出循环,但它仍然不起作用。

请帮助!

Thans提前“!

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 

您不需要select或激活 – 只需使用工作表对象限定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 

尝试

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

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