作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我在 Do/With 函数下添加一个项目时,我有一段代码会引发错误 91。 (感谢克里斯尼尔森的代码)
Dim ws As Worksheet
Dim SrchRng As Range
Dim SearchValues() As Variant
Dim cl As Range, addr As String
Dim i As Long
SearchValues = Array(217, 317, 298)
Set ws = ActiveSheet
With ws
Set SrchRng = Range(.Cells(1, 7), .Cells(.Rows.Count, 7).End(xlUp))
End With
For i = LBound(SearchValues) To UBound(SearchValues)
Set cl = SrchRng.Find(SearchValues(i), LookIn:=xlValues)
If Not cl Is Nothing Then
addr = cl.Address
Do
With cl.EntireRow
.Font.ColorIndex = 2
.Interior.ColorIndex = 1
End With
Set cl = SrchRng.FindNext(cl)
Loop While cl.Address <> addr
End If
Next
Dim ws As Worksheet
Dim SrchRng As Range
Dim SearchValues() As Variant
Dim cl As Range, addr As String
Dim i As Long
SearchValues = Array(217, 317, 298)
Set ws = ActiveSheet
With ws
Set SrchRng = Range(.Cells(1, 7), .Cells(.Rows.Count, 7).End(xlUp))
End With
For i = LBound(SearchValues) To UBound(SearchValues)
Set cl = SrchRng.Find(SearchValues(i), LookIn:=xlValues)
If Not cl Is Nothing Then
addr = cl.Address
Do
With cl.EntireRow
.Font.ColorIndex = 2
.Interior.ColorIndex = 1
.ClearContents
End With
Set cl = SrchRng.FindNext(cl)
Loop While cl.Address <> addr
End If
Next
最佳答案
当您正在清除单元格时,cl
可能是 Nothing
所以你需要要么删除循环外的范围,要么添加一个测试 Nothing
方法1会更快
方法1 - 单次删除范围
Sub A()
Dim ws As Worksheet
Dim SrchRng As Range
Dim SearchValues() As Variant
Dim cl As Range, addr As String
Dim i As Long
Dim rng2 As Range
SearchValues = Array(217, 317, 298)
Set ws = ActiveSheet
With ws
Set SrchRng = Range(.Cells(1, 7), .Cells(.Rows.Count, 7).End(xlUp))
End With
For i = LBound(SearchValues) To UBound(SearchValues)
Set rng2 = Nothing
Set cl = SrchRng.Find(SearchValues(i), LookIn:=xlValues)
If Not cl Is Nothing Then
addr = cl.Address
Do
If Not rng2 Is Nothing Then
Set rng2 = cl.EntireRow
Else
Set rng2 = Union(rng2, cl.EntireRow)
End If
Set cl = SrchRng.FindNext(cl)
Loop While Not cl Is Nothing
End If
If Not rng2 Is Nothing Then
With rng2
.Font.ColorIndex = 2
.Interior.ColorIndex = 1
.ClearContents
End With
End If
Next
End Sub
With cl.EntireRow
.Font.ColorIndex = 2
.Interior.ColorIndex = 1
.ClearContents
End With
Set cl = SrchRng.FindNext(cl)
Loop While Not cl is Nothing
关于将项目添加到 With...End With 时出现 excel 错误 91,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23443403/
我是一名优秀的程序员,十分优秀!