Excel VBA:应用程序定义或对象定义的错误

我已经写了一些代码来查找excel文件中的括号组,并将它们之间的单元格的内容白掉。 在我得到错误信息之前,我有26-27行的代码。

这里是代码:

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 

该行发生错误:

 Do While Cells(rowIndex, colIndex).Value <> "]" 

我试着join:

 With ActiveSheet 

随着 。 每个单元命令之前,但没有任何区别。 任何帮助是极大的赞赏。

如果其中一个包含[]的单元格可能具有stream氓前导空格/非中断空格,则应该进行通配符比较。 此外,工作表的MATCHfunction可以通过通配符search更有效地定位包围单元,而不是循环遍历每个单元格。

 Sub hide_cell_values() Dim whiteOut As String '<~~ using alternate method .NumberFormat ;;; Dim rw As Long, n As Long, f As Long, l As Long whiteOut = ";;;" 'custom cell number format to show nothing in cell With ActiveSheet 'process row by row in the .UsedRange With .Range(.Cells(1, 1), .Cells.SpecialCells(xlCellTypeLastCell)) For rw = 1 To .Rows.Count ' check for existance of matching pairs If Not IsError(Application.Match("*[*", .Rows(rw), 0)) And _ Application.CountIf(.Rows(rw), "*[*") = _ Application.CountIf(.Rows(rw), "*]*") Then ' [ and ] pairs exist and match in row. f = 0: l = 0 For n = 1 To Application.CountIf(.Rows(rw), "*[*") 'this looks complicated but it just references the cells between [ & ] f = Application.Match("*[*", .Rows(rw).Cells.Offset(0, l), 0) + l + 1 ' last safety check to ensure that [ comes before ] If Not IsError(Application.Match("*]*", .Rows(rw).Cells.Offset(0, f), 0)) Then l = Application.Match("*]*", .Rows(rw).Cells.Offset(0, f), 0) + f - 1 With .Range(.Cells(rw, f), .Cells(rw, l)) 'this is a better method of not displaying text in a cell .NumberFormat = whiteOut '<~~ eg ;;; 'the old method of white-text-on-white-background (not reliable as .Interior.Color can change) '.Font.Color = vbWhite End With End If Next n Else ' [ and ] pairs do not match or do not exist in row. do nothing. End If Next rw End With End With End Sub 

我select了自定义的单元格格式;;; 而不是将字体颜色更改为RGB(255, 255, 255) (请参阅脚注1)。 连续三个分号的Range.NumberFormat属性只显示任何内容; 一个白色的字体的明显的可见性受到单元格的Range.Interior.Color属性 , 工作表背景 ,甚至计算机的系统设置中的“窗口背景”。

隐藏单元格内容之前
在运行之前

隐藏单元格后的内容
运行子之后

在上面和之后的图片中,您可以看到,D2保留了其Range.Value属性 (在公式栏中可见),而在工作表上没有任何东西。 注意:单元格值仍然可以从单元格中复制,但是这也是使用vbWhite方法的一个警告。


¹ 对于基本VBA调色板,有预定义的RGB长型常量。 RGB(255, 255, 255)等于vbWhite Color Constants中提供的完整列表。