【问题标题】:Excel vba for determining a cell based on color and then coloring the next uncolored row directly above itExcel vba,用于根据颜色确定单元格,然后为其正上方的下一个未着色行着色
【发布时间】:2014-09-29 01:57:44
【问题描述】:

我有一张在单击按钮时自动格式化的工作表。我的问题是尝试根据另一行的当前颜色为一行着色。基本上这张表是这样的:

数字零件级别(0-1-2- 或 3)---- 序列号 ------ 零件名称 ------ etcc..

数字零件级别(0-1-2- 或 3)---- 序列号 ------ 零件名称 ------ etcc..

数字零件级别(0-1-2- 或 3)---- 序列号 ------ 零件名称 ------ etcc..

我目前将组件中的零件格式化为绿色,这是基于它们在第 1 列中的数字零件级别,对于装配组件,所有零件级别都是 2,所以这很容易。我的问题来了,我想将作为装配组件标题的行格式化为蓝色,装配组件的标题但是与整个组件中的所有其他部分一样,部件级别为 1,所以我不能简单地要求 excel用蓝色为所有级别 1 着色!

所以我最初尝试使用偏移命令来查找绿色行并选择其上方的行以突出显示蓝色,这不起作用,因为 2 级组件的数量不同,因此标题组件并不总是直接位于其上方的行.我没有其他类型的数据可供搜索以尝试为蓝色单元格着色。

我正在考虑一个代码,它在行中搜索直到找到一条绿线,然后从那里向上移动,直到找到下一条未着色的线并将其涂成蓝色。然后移动到下一行,直到到达范围的末尾。

我不知道如何处理这样的事情,有人帮忙吗?谢谢!

【问题讨论】:

    标签: vba excel search


    【解决方案1】:
    Sub colorCells()
        Dim x, i as Integer, color As Long
        Dim flg As Boolean
    
        'set the flag
        flg = True
        For Each x In Range("A:A")
            color = x.Interior.color
            If color = vbGreen Then
                If flg Then
                    For i = x.Row To 1 Step -1
                    x.Offset(-1, 0).Interior.color = vbBlue
                    flg = False
                End If
            Else: flg = True
            End If
        Next x
    End Sub
    

    要获取颜色代码,请执行以下操作:

    Sub getColor()
        MsgBox ActiveCell.Interior.Color
    End Sub
    

    如果您需要在任何绿色行块上方找到第一个未着色的行,请尝试以下操作:

    Sub colorCells()
        Dim x, color As Long, i As Integer
        Dim flg As Boolean
    
        'set the flag
        flg = True
        For Each x In Range("A:A")
            color = x.Interior.color
            If color = vbGreen Then
                If flg Then
                    For i = 1 To x.Row
                        If x.Offset(-i, 0).Interior.color = 16777215 Then
                            x.Offset(-i, 0).Interior.color = vbBlue
                            Exit For
                        End If
                    Next i
                    flg = False
                End If
            Else: flg = True
            End If
        Next x
    End Sub
    

    【讨论】:

    • 谢谢,但这不起作用,它实际上根本没有着色任何东西,但如果它看起来只有一个偏移命令来为绿色正上方的行着色,不是吗?这行不通,因为一行中有多个绿色行,而蓝色行并不总是正上方的行。基本上这是我添加的颜色查找代码:
    • '使用 .Cells(Lrow, "A") If Not IsError(.Value) Then If .Value = "2" Then .EntireRow.Interior.color = vbGreen End If End With Dim x, color as Long Dim rng as Range Rng=”A:A” For Each x in rng
    • color = x.Interior.Color If color = vbGreen Then x.offset(-1,0).Interior.Color = vbBlue End If Next Next Lrow End With ActiveWindow.View = ViewMode With Application 。 ScreenUpdating = True .Calculation = CalcMode End With
    猜你喜欢
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    相关资源
    最近更新 更多