I've written some code to look for sets of brackets in an excel file and white out the contents of the cells in between them. The code I have works for 26-27 lines before I get the error message.
Here is the code:
Sub macro()
Dim white As Long
Dim rowIndex As Long
Dim colIndex As Long
Dim lastRow As Long
Dim lastCol As Long
white = RGB(Red:=255, Green:=255, Blue:=255)
With ActiveSheet
lastRow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
lastCol = .Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
For rowIndex = 1 To lastRow
For colIndex = 1 To lastCol
If .Cells(rowIndex, colIndex).Text = "[" Then
colIndex = colIndex + 1
Do While .Cells(rowIndex, colIndex).Value <> "]"
.Cells(rowIndex, colIndex).Font.Color = white
colIndex = colIndex + 1
Loop
End If
Next colIndex
Next rowIndex
End With
End Sub
The error occurs on this line:
Do While Cells(rowIndex, colIndex).Value <> "]"
I tried adding in:
With ActiveSheet
Along with . before each Cell command but it did not make a difference. Any help is greatly appreciated.
If one of the cells containing
[
or]
may have rogue leading trailing spaces/non-breaking spaces then a wildcard comparison should be made. Additionally, the worksheet's MATCH function can locate the bracketing cells with a wildcard search more efficiently than looping through each cell row-by-row.I have opted for a custom cell number format of
;;;
rather than altering the font color toRGB(255, 255, 255)
(see footnote ¹). A Range.NumberFormat property of three semi-colons in a row simply shows nothing; a white font's apparent visibility is subject to the cell's Range.Interior.Color property, the worksheet backgroun or even the 'Window background' in the computer's system settings.Before running sub
After running sub
In the before and after images above, you can see that D2 retains its Range.Value property (visible in the formula bar) while showig nothing on the worksheet. Note: cell values can still be copied from a cell displaying nothing but that is a caveat of using the
vbWhite
method as well.¹ There are predefined RGB long type constants for the basic VBA pallette.
RGB(255, 255, 255)
is equal tovbWhite
. Full list available at Color Constants.