VBA单元格格式错误

时间:2015-03-27 20:40:35

标签: excel vba

我正在尝试使用for循环格式化一组单元格(稍后是条件while循环)

我收到错误'1004'

对象“全局”失败的方法“范围”

我无法弄清楚如何将单元格值转换为不会引发此错误的范围值。单元格(x,y)本身也会抛出错误

提前致谢

    For row = 2 To 5

    With Range(Cells(row, 5)).Interior
        .Pattern = xlPatternRectangularGradient
        .Gradient.RectangleLeft = 0.5
        .Gradient.RectangleRight = 0.5
        .Gradient.RectangleTop = 0.5
        .Gradient.RectangleBottom = 0.5
        .Gradient.ColorStops.Clear
    End With
    With Range(Cells(row, 5)).Interior.Gradient.ColorStops.Add(0)
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = 0
    End With
    With Range(Cells(row, 5)).Interior.Gradient.ColorStops.Add(1)
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = -0.250984221930601
    End With

Next row

3 个答案:

答案 0 :(得分:1)

为什么你甚至会循环?

Sub SO()

    With Range(Cells(2, 5), Cells(5, 5)).Interior
        .Pattern = xlPatternRectangularGradient
        .Gradient.RectangleLeft = 0.5
        .Gradient.RectangleRight = 0.5
        .Gradient.RectangleTop = 0.5
        .Gradient.RectangleBottom = 0.5
        .Gradient.ColorStops.Clear
        With .Gradient.ColorStops.Add(0)
            .ThemeColor = xlThemeColorDark1
            .TintAndShade = 0
        End With
        With .Gradient.ColorStops.Add(1)
            .ThemeColor = xlThemeColorAccent6
            .TintAndShade = -0.250984221930601
        End With
    End With

End Sub

答案 1 :(得分:0)

无需Range()

只需Cells(row, 5).Interior

  For row = 2 To 5

    With Cells(row, 5).Interior
        .Pattern = xlPatternRectangularGradient
        .Gradient.RectangleLeft = 0.5
        .Gradient.RectangleRight = 0.5
        .Gradient.RectangleTop = 0.5
        .Gradient.RectangleBottom = 0.5
        .Gradient.ColorStops.Clear
    End With
    With Cells(row, 5).Interior.Gradient.ColorStops.Add(0)
        .ThemeColor = xlThemeColorDark1
        .TintAndShade = 0
    End With
    With Cells(row, 5).Interior.Gradient.ColorStops.Add(1)
        .ThemeColor = xlThemeColorAccent6
        .TintAndShade = -0.250984221930601
    End With

Next row

答案 2 :(得分:0)

摆脱Range()

With Cells(row, 5).Interior

您想要使用

Cells(row, col) 
Cells(2, 5)

Range(addressString)
Range("E2")

如果您没有将工作表对象放在其中任何一个之前,如果您在工作表模块中工作,它们将引用活动表或“我”。

供参考:

Dim ws as worksheet
set ws = Thisworkbook.sheets("Sheet1")

ws.cells(2, 5)
ws.Range("E2")