如何修改此VBA代码以便它在我的工作簿中的所有工作表上运行?

时间:2018-05-08 11:39:59

标签: excel vba excel-vba excel-2016

我正在使用Excel 2016,我有以下VBA代码,用于删除活动工作表中所有单元格(基于提供的RGB数字)中的突出显示。:

Sub RemoveSpecificColorFill()
'PURPOSE: Remove a specific fill color from the spreadsheet
 Dim cell As Range

'Turn off ScreenUpdating (speeds up code)
Application.ScreenUpdating = False

'Loop through each cell in the ActiveSheet
 For Each cell In ActiveSheet.UsedRange

'Check for a specific fill color
  If cell.Interior.Color = RGB(255, 255, 0) Then

    'Remove Fill Color
      cell.Interior.Color = xlNone

  End If

Next cell

End Sub

我想更新代码,以便VBA代码在该工作簿中的所有工作表上运行,而不是在活动工作簿中运行。

4 个答案:

答案 0 :(得分:4)

这比循环遍历所有单元格要快一些:

Sub RemoveSpecificColorFill()
    Dim ws As Worksheet
    With Application
        .FindFormat.Clear
        .ReplaceFormat.Clear
        .FindFormat.Interior.Color = RGB(255, 255, 0)
        .ReplaceFormat.Interior.Color = xlNone
        For Each ws In ThisWorkbook.Worksheets
            ws.Cells.Replace What:="", Replacement:="", SearchFormat:=True, ReplaceFormat:=True
        Next ws
        .FindFormat.Clear
        .ReplaceFormat.Clear
    End With
End Sub

答案 1 :(得分:1)

您可以在代码周围添加第二个循环,并遍历工作簿的所有工作表。像这样的东西

For Each ws In Worksheets

    For Each cell In ws.UsedRange

答案 2 :(得分:1)

这对你有用。它只是一个遍历每个工作表然后运行代码的子

Sub forEachWs()
    application.screenupdating = false
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        Call RemoveSpecificColorFill(ws)
    Next
    application.screenupdating = true
End Sub

Sub RemoveSpecificColorFill(ws As Worksheet)
'PURPOSE: Remove a specific fill color from the spreadsheet
Dim cell As Range


'Loop through each cell in the ActiveSheet
 For Each cell In ws.UsedRange

'Check for a specific fill color
  If cell.Interior.Color = RGB(255, 255, 0) Then

    'Remove Fill Color
      cell.Interior.Color = xlNone

  End If

Next cell

End Sub

答案 3 :(得分:1)

你应该在完成屏幕更新之后重新开启屏幕更新。

Sub RemoveSpecificColorFill()
'PURPOSE: Remove a specific fill color from the spreadsheet
 Dim cell As Range, wks As Worksheet

 'Turn off ScreenUpdating (speeds up code)
  Application.ScreenUpdating = False
  For Each wks In ThisWorkbook.Worksheets
  'Loop through each cell in the ActiveSheet
  For Each cell In wks.UsedRange

  'Check for a specific fill color
   If cell.Interior.Color = RGB(255, 255, 0) Then

   'Remove Fill Color
     cell.Interior.Color = xlNone

       End If

   Next cell
   Next wks
   Application.ScreenUpdating = True
   End Sub