[英]delete all cells of a certain color
這似乎相對簡單,據我了解,這是可能的。 但是我似乎無法弄清楚或者無法在互聯網上找到我想要的東西。
我在A列中有一些excel數據,一些數據是藍色(0,0,255),一些數據是紅色(255,255,255),一些數據是綠色(0,140,0)。 我要刪除所有藍色數據。
有人告訴我:
Sub test2()
Range("A2").DisplayFormat.Font.Color
End Sub
會給我顏色...但是當我運行它時,它說該屬性無效使用並突出顯示.color
相反,我單擊了以下內容:字體顏色下拉菜單,然后是更多顏色,然后是自定義顏色,然后我看到藍色的數據為(0,0,255)
因此,我嘗試了:
Sub test()
Dim wbk As Workbook
Dim ws As Worksheet
Dim i As Integer
Set wbk = ThisWorkbook
Set ws = wbk.Sheets(1)
Dim cell As Range
With ws
For Each cell In ws.Range("A:A").Cells
'cell.Value = "'" & cell.Value
For i = 1 To Len(cell)
If cell.Characters(i, 1).Font.Color = RGB(0, 0, 255) Then
If Len(cell) > 0 Then
cell.Characters(i, 1).Delete
End If
If Len(cell) > 0 Then
i = i - 1
End If
End If
Next i
Next cell
End With
End Sub
我在多個地方在網絡上找到了此解決方案,但是當我運行它時,似乎什么都沒有發生。
您可以使用xlFilterFontColor
運算符使用Range
對象的Autofilter()
方法;
Sub test()
With ThisWorkbook.Sheets(1)
With .Range("A1", .Cells(.Rows.Count, 1).End(xlUp))
.AutoFilter Field:=1, Criteria1:=RGB(0, 0, 255), Operator:=xlFilterFontColor
If Application.WorksheetFunction.Subtotal(103, .Cells) > 0 Then .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).ClearContents
End With
.AutoFilterMode = False
If .Range("A1").Font.Color = RGB(0, 0, 255) Then .Range("A1").ClearContents ' check first row, too (which is excluded by AutoFilter)
End With
End Sub
這是基本操作,如果未刪除具有藍色字體的單元格,則該字體是另一種顏色。 更改范圍以滿足您的需求。
For Each cel In ActiveSheet.Range("A1:A30")
If cel.Font.Color = RGB(0, 0, 255) Then cel.Delete
Next cel
已更新,以允許用戶選擇帶有字體顏色的列中的第一個單元格,獲取字體顏色,並清除所有與字體顏色匹配的單元格。
Dim rng As Range
Set rng = Application.InputBox("Select a Cell:", "Obtain Range Object", Type:=8)
With ActiveSheet
Dim lr As Long
lr = Cells(Rows.Count, 1).End(xlUp).Row
Dim x As Long
x = rng.Row
For i = lr To x Step -1
If .Cells(i, 1).Font.Color = rng.Font.Color Then .Cells(i, 1).Clear
Next i
End With
遵循以下步驟,使用Union
將所有符合條件的單元格聚集在一起,並一次性刪除。 如果要單獨刪除整個行,則始終需要向后循環。 一鍵刪除/清除效率更高。
Sub test()
Dim wbk As Workbook, ws As Worksheet
Dim i As Long, currentCell As Range, unionRng As Range
Set wbk = ThisWorkbook
Set ws = wbk.Worksheets("Sheet1")
With ws
For Each currentCell In .Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row) '<==assuming actual data present
If currentCell.Font.Color = RGB(0, 0, 255) Then
If Not unionRng Is Nothing Then
Set unionRng = Union(currentCell, unionRng)
Else
Set unionRng = currentCell
End If
End If
Next
End With
If Not unionRng Is Nothing Then unionRng.Delete
End Sub
Option Explicit
Sub test2()
Dim cel As Range
Dim LR As Long
LR = Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
For Each cel In ActiveSheet.Range("A1:A" & LR)
If cel.Font.Color = RGB(0, 0, 255) Then cel.ClearContents
Next cel
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.