找出哪些单元格具有某种颜色并列出它们

时间:2018-04-26 06:01:56

标签: excel excel-vba vba

我正在创建一个英语活动,您可以通过使用我大声说出的网格坐标绘制图片来练习字母和数字。顶行有字母,左列有数字,使用两者的组合,您可以指定哪个单元格中的颜色。

在Excel中执行此操作,我手动绘制像素图像(通过打印图像和绘图框然后在Excel单元格中着色背景颜色),然后写出答案键(A,BC等中的黑色单元格列表) 。,A,B,C等红细胞)手动。这没关系,但有时会出错。

我想知道一种方法来列出哪些单元格中有一定的背景颜色。最终,如果我能像下面的例子那样列出它会很棒:

  • 黑色
  • A:1,2,3,4
  • B:4,5,6
  • C:4,5,6

我听说公式无法使用excel,我需要使用宏,这是我没有经验的。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

假设您的Excel工作簿至少有一个包含彩色单元格的工作表(我将其称为“Sheet1”)和一个额外显示查询结果的工作表,我们称之为“Sheet2”,代码清单有色单元格的地址可能如下所示:

Sub ColorIndex()

    Dim RNG         As Range    'the address of the cell you want to check
    Dim lnCol       As Long     'the column of the cell looked at
    Dim lnRow       As Long     'the row of the cell looked at
    Dim c           As Long     'the column on Sheet2 and...
    Dim r           As Long     'the row on Sheet2 where the address of the coloured cell is written to

    c = 1
    r = 1

    For lnCol = 1 To 100  'adjust if necessary, see below

        For lnRow = 1 To 100  'adjust if necessary, see below
        Set RNG = Worksheets("Sheet1").Cells(lnRow, lnCol)

            If RNG.Interior.ColorIndex = 1 Then
                Worksheets("Sheet2").Cells(r, c) = RNG.Address(ReferenceStyle:=xlR1C1) 'Address of the coloured cell on Sheet1 as Row x / Column y
                r = r + 1 'next match written in next row
                ElseIf RNG.Interior.ColorIndex = 2 Then
                    Worksheets("Sheet2").Cells(r, c+1) = RNG.Address(ReferenceStyle:=xlR1C1)
            End If

        Next lnRow

    Next lnCol

End Sub

请注意,此代码仅检查行/列1到100。如果您要检查的范围较大,请相应地调整数字。

希望这有帮助!