1

我正在使用 Excel 的 Active Sheet 对象来循环遍历行和列。

我需要更改单元格的背景颜色,但在此行上出现应用程序定义或对象定义错误

ws.Cells(rw, 4).Interior.ColorIndex = 0

这是我正在使用的代码

Dim ws As Worksheet

Set ws = ActiveSheet

With ws


For rw = 7 To ws.Rows.Count

   For col = 2 To 12

    'Check the first column and if null then exit

    If ws.Cells(rw, 2) = "" Then
        Exit Sub
    End If

   'Check if article code is less than eight digits
    If Len(ws.Cells(rw, 4)) < 8 Then
        ws.Cells(rw, 4).Interior.ColorIndex = 3
    Else
        ws.Cells(rw, 4).Interior.ColorIndex = 0
    End If


  Next col

Next rw

End With

有什么想法吗?

4

1 回答 1

2

代码没有问题。您收到该错误是因为您的工作表受到保护。您需要取消保护工作表,然后更改单元格颜色。完成颜色更改后,您可以重新保护它。请参阅此代码。

Sub Sample()
    Dim ws As Worksheet
    Dim Mypassword As String

    '~~> Change password here
    Mypassword = "Blah Blah"

    Set ws = ActiveSheet

    With ws
        '~~> Unprotect sheet
        .Unprotect Mypassword
        For rw = 7 To .Rows.Count
            For col = 2 To 12
                'Check the first column and if null then exit
                If .Cells(rw, 2).Value = "" Then Exit Sub

                'Check if article code is less than eight digits
                If Len(.Cells(rw, 4)) < 8 Then
                    .Cells(rw, 4).Interior.ColorIndex = 3
                Else
                    .Cells(rw, 4).Interior.ColorIndex = 0
                End If
            Next col
        Next rw
        '~~> Reprotect sheet
        .Protect Mypassword
    End With
End Sub
于 2012-08-14T12:24:59.087 回答