简体   繁体   English

在Excel中使用VBA遍历特定颜色的单元格范围

[英]Looping through range of cells of a particular colour using VBA in Excel

I'm looking for help with a Macro which would loop through all the cells in a specified row (8). 我正在寻找有关宏的帮助,该宏将遍历指定行(8)中的所有单元格。 However in order to complicate matters I'm only concerned with cells of a particular colour (Blue) as there are many cells in the 8th row but some are green. 但是,为了使事情复杂化,我只关注特定颜色(蓝色)的单元格,因为第8行中有很多单元格,但有些是绿色的。 In order to complicate matters even further of the subset of cells that are blue I only want to highlight those that contain the text "product", "UOM" or "Pack size" and "New Unit Price" Once found I would like to highlight the columns which these cells are the headers of. 为了使蓝色单元格的子集进一步复杂化,我只想突出显示包含“产品”,“ UOM”或“包装尺寸”和“新单价”文本的单元格。一旦找到,我想突出显示这些单元格是其标题的列。 I then would like to copy those cells and paste them into a new workbook. 然后,我想复制这些单元格并将其粘贴到新的工作簿中。

It seems there are a few ways to do this, I could either loop through all the cells on the 8th row with the condition being highlight column If cell contains the specified text AND cell is blue. 似乎有几种方法可以执行此操作,我可以在第8行的所有单元格中进行循环,条件是突出显示列。如果单元格包含指定的文本并且单元格为蓝色。 However this seems inefficient. 但是,这似乎效率很低。 Or I could loop through all cells and stop once a green cell has been reached. 或者,我可以遍历所有单元格,并在达到绿色单元格后停止。 This would give me the range of blue cells. 这将为我提供蓝色单元格的范围。 I could then loop through the range of blue cells highlighting all columns for which the header contains the specified text. 然后,我可以遍历蓝色单元格的范围,突出显示标题包含指定文本的所有列。 I'm only new to VBA and don't really know the syntax terribly well. 我只是VBA的新手,并不十分了解语法。 I also had trouble finding information on looping through cells which contain only a specified colour. 我也很难找到有关循环通过仅包含指定颜色的单元的信息。 Anyone know how this could be done? 有人知道该怎么做吗?

Cheers! 干杯!

Public Sub HighlightColumns(ByVal w As Worksheet)
  Dim c As Range
  Dim found As Range

  For Each c In Application.Intersect(w.Rows(8), w.UsedRange).Cells
    If c.Interior.Color = vbBlue Then
      Select Case c.Value
      Case "product", "UOM", "Pack size", "New Unit Price"
        If found Is Nothing Then Set found = c Else Set found = Application.Union(found, c)
      End Select
    End If
  Next

  If Not found Is Nothing Then found.EntireColumn.Select
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM