2015-12-29 38 views
0

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

但是,此代码颜色正确的单元格,但在工作表DATABASE而不是CALENDAR。 正如您所看到的,我尝试激活并选择表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 

回答

2

你并不需要选择或激活 - 只要你的资格和Range电话Cells与工作表对象:

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 
0

尝试

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

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