2017-04-06 144 views
-2

得到一個「編譯錯誤:無法分配給只讀屬性」爲以下幾點:無法分配給只讀屬性VBA

With wsData.Shapes("Rectangle 1").Fill 

    .Pattern = xlGrid 
    .ForeColor.RGB = RGB(255, 0, 0) 

End With 
+2

你有問題嗎? – CLR

+1

嘗試'.BackColor.RGB = RGB(255,0,0)' –

+0

謝謝大衛。但是,我仍然收到此錯誤 - 「編譯錯誤:無法分配給只讀屬性」。 – ajdesanti

回答

1

你缺少中間的ShapeRange屬性:

With wsData.Shapes("Rectangle 1").ShapeRange 

全碼:

With wsData.Shapes("Rectangle 1").ShapeRange 
    With .Fill 
     .Pattern = xlGrid 
     .BackColor.RGB = RGB(255, 0, 0) 
    End With 
End With 

編輯1:代碼可能出現的錯誤處理

Option Explicit 

Sub ColorChape() 

Dim wsData  As Worksheet 
Dim myShp  As Shape 

Set wsData = Worksheets("Sheet1") ' <-- modify to your sheet's name 

On Error Resume Next 
Set myShp = wsData.Shapes("Rectangle 1") 
On Error GoTo 0 

If myShp Is Nothing Then ' <-- unable to set the shape, doesn't exist in specified sheet 
    MsgBox "`Rectangle 1` Shape doesn't exist in " & wsData.Name & " sheet!", vbCritical 
Else 
    With myShp 
     With .Fill 
      .BackColor.RGB = RGB(255, 0, 0) 
      ' rest of your code goes here 

     End With 
    End With 
End If 

End Sub 
+0

嗨,謝謝你的回覆。沒有,也沒有工作。 – ajdesanti

+0

@ajdesanti你確定你有一個'''Rectangle 1''Shape?在'wsData'工作表中? –

+0

錯誤發生是因爲「.Pattern = xlGrid」,因爲代碼在我運行這個函數時工作正常 - 使用wsData.Shapes(「Rectangle 1」)。填充 .ForeColor.RGB = RGB(255,0,0) End With – ajdesanti

相關問題