无法分配给只读属性vba

时间:2017-04-06 15:06:10

标签: excel-vba vba excel

获取以下内容的“编译错误:无法分配给只读属性”:

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

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

End With

1 个答案:

答案 0 :(得分: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