2017-07-31 51 views
0

我是VBA的新手,正在通過練習學習它,其中一個宏是爲紅色框着色如果我點擊宏按鈕。我錄一個宏初步檢查什麼的VBA代碼,它用來做在VBA中選擇活動單元

Sub MakeMeRed() 
' 
' MakeMeRed Macro 
' 
    With Selection.Interior 
     .Pattern = xlSolid 
     .PatternColorIndex = xlAutomatic 
     .Color = 192 
     .TintAndShade = 0 
     .PatternTintAndShade = 0 
    End With 
End Sub 

我用Google搜索周圍發現有選擇活性細胞的另一種方法,所以我想這種方式來填充單元格。

Sub TestMacro() 
' 
' TestMacro Macro 
' 
    With ActiveCell 
     '.Value = "250" 
     .Color = 200 
    End With 
End Sub 

但是,這段代碼不起作用,它不會填充選定單元格的顏色。你能指出我要出錯的地方嗎?

+1

變化'ActiveCell'到'Selection.Interior' –

+0

和改變。顏色以.interior.color。在旁註中,使用ActiveCell並不明智,最好明確引用單元格。例如A1變爲Thisworkbook.Thisworksheet.Cells(1,1)(你可以用顯式的工作簿或工作表來替換這個工作簿和這個工作表) – Luuklag

+0

Hey @Scott,任何原因Active Cell都不起作用,因爲根據我的理解,它也是指向當前單元格,可以請讓我知道區別以及何時使用 –

回答

0

爲了等於兩者,該部分中的ActiveCell是第一個中的選擇。要改變顏色,你需要在內部部分的某處滑動。您可以使用With ActiveCell.Interior或使用塊.Interior.Color = 200

2

這裏有2方法來引用單元格內的顏色。使用ActiveCell.Interior.ColorIndexActiveCell.Interior.ColorActiveCell.Interior.Color可以得到4個不同的值。

Sub TestMacro() 

    With ActiveCell 
     .Value = 1 
     .Interior.ColorIndex = 3 

     .Offset(1, 1) = 21 
     .Offset(1, 1).Interior.Color = RGB(255, 0, 0) 

     .Offset(1, 2) = 22 
     .Offset(1, 2).Interior.Color = vbRed 'vbRed = 255 

     .Offset(1, 3) = 23 
     .Offset(1, 3).Interior.Color = "&HFF" 'FF = 255; &H is for typeinfo 

     .Offset(1, 4) = 24 
     .Offset(1, 4).Interior.Color = 255 
    End With 

End Sub 

它看起來像這樣:

enter image description here