excel 组合“Set”和“If”计数未隐藏的红细胞

2wnc66cl  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(154)

每个单元格的值为0,该行将被隐藏。以及在最小值和最大值之外的任何值 将是红色的。

Set mr = Sheets("COA").Range("i11:i34")
For Each cell In mr
    If cell.DisplayFormat.Interior.Color = vbRed Then
        MsgBox

该代码与预期不同,因为红色隐藏单元格也被计算在内。
我以前问过,人们回答

Set rng = Range("Your range").SpecialCells(xlCellTypeVisible)

但如果我有两个条件呢如何合并set和if?
条件A =如果活动单元格为红色,则返回到用户表单并
条件B =如果活动单元格不是红色,则卸载用户表单

Set Rng = Range("i11:i34").SpecialCells(xlCellTypeVisible)
If ActiveCell.DisplayFormat.Interior.Color = vbRed Then
    MsgBox "bla bla bla", vbCritical + vbOKOnly, ""
    
    'Show Excel and resize the UserForm2
    Application.Visible = True
    Me.Height = 405
    Me.Width = 730.5
End If
    
If ActiveCell.DisplayFormat.Interior.Color = 0 Then
    MsgBox "bla bla bla", vbCritical + vbOKOnly, ""
End If
brc7rcf0

brc7rcf01#

这就是你要尝试的吗?
请记住,编写清晰简洁的代码总是更好的。最好也完全限定对象。还有一件事当使用SpecialCells时,始终将它们夹在On Error Resume NextOn Error GoTo 0之间,如我下面所示,否则您可能会得到错误。
顺便说一句,我没有使用If-Then-Else。我用Select Case

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim rng As Range
    Dim VisibleCells As Range
    Dim aCell As Range
    
    '~~> Change this to the relevant sheet
    Set ws = Sheet1
    
    Set rng = ws.Range("I11:I34")
    
    On Error Resume Next
    Set VisibleCells = rng.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    
    If Not VisibleCells Is Nothing Then
        For Each aCell In VisibleCells
            Select Case aCell.DisplayFormat.Interior.Color
                Case vbRed
                    MsgBox "Blah1", vbCritical + vbOKOnly, ""
                    'Show Excel and resize the UserForm2
                    'Application.Visible = True
                    'Me.Height = 405
                    'Me.Width = 730.5
                Case 0
                    MsgBox "Blah2", vbCritical + vbOKOnly, ""
                '~~> For no color use the below
                'Case 16777215
                    'MsgBox "Blah3", vbCritical + vbOKOnly, ""
            End Select
        Next aCell
    End If
End Sub

相关问题