[英]Excel VBA: Application defined or Object defined error
我已经编写了一些代码以在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 <> "]"
我尝试添加:
With ActiveSheet
随着 。 在每个Cell命令之前,但没有任何区别。 任何帮助是极大的赞赏。
如果包含[
或]
的单元格之一可能具有流氓前导尾随空格/不间断空格,则应进行通配符比较。 此外,工作表的“ 匹配”功能可以比使用逐行循环遍历每个单元格更有效地使用通配符搜索来定位包围式单元格。
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 '<~~ e.g. ;;;
'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
我选择了自定义单元格格式;;;
而不是将字体颜色更改为RGB(255, 255, 255)
(请参阅脚注¹)。 连续三个分号的Range.NumberFormat属性仅显示任何内容; 白色字体的明显可见性取决于单元格的Range.Interior.Color属性 ,计算机系统设置中的工作表背景 ,甚至是“窗口背景”。
在上面的之前和之后的图像中,您可以看到D2保留其Range.Value属性 (在编辑栏中可见),而在工作表上不显示任何内容。 注意:仍然可以从不显示任何内容的单元格复制单元格值,但这也说明了使用vbWhite
方法。
¹ 基本VBA调色板有预定义的RGB长型常量。 RGB(255, 255, 255)
等于vbWhite
。 完整列表可在“ 颜色常数”中找到 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.