【问题标题】:Application-defined error when looping through ranges循环遍历范围时应用程序定义的错误
【发布时间】:2019-05-20 09:59:39
【问题描述】:
我正在尝试遍历不同的范围,将具有值“1”的单元格替换为另一个值/格式。
如果我一一使用范围,效果会很好。但是,当我尝试组合不同的范围并循环遍历数组时,我在 .Pattern 部分遇到了应用程序定义的运行时错误。
我读过它与未定义工作表有关,但我不确定如何在此设置中正确执行此操作。
我已经试过了:
- 没有 i-loop 的单一范围代码:代码有效
- 将 ActiveSheet 添加到 with-loop:With Activesheet.Range(DRng).cell:失败
- 添加引用范围/工作表的不同方式:失败
-
cell.select before with cell.interior
Sub SetTelSlot()
Dim cell As Range
Dim DRng(1 To 5) As Range
Dim i As Long
Set DRng(1) = Range("E7:AB33")
Set DRng(2) = Range("E45:AB71")
Set DRng(3) = Range("E82:AB108")
Set DRng(4) = Range("E119:AB145")
Set DRng(5) = Range("E156:AB182")
For i = LBound(DRng) To UBound(DRng)
For Each cell In DRng(i)
If cell.Value = "1" Then
With cell.Interior
.Pattern = xlSolid '==>this is giving the error
.PatternColorIndex = xlAutomatic
.Color = RGB(0, 204, 153)
.TintAndShade = 0
.PatternTintAndShade = 0
End With
cell.Font.Bold = SetBold
cell.Font.Color = vbBlack
cell.Value = "T"
End If
Next cell
Next i
End Sub
【问题讨论】:
标签:
arrays
excel
vba
loops
【解决方案1】:
作为一个建议:您可以只构建一个包含所有范围的单个范围对象,并在此范围内搜索匹配的单元格,而不是遍历每个范围中的每个单元格:
Sub SetTelSlot()
Dim c As Range, DRng As Range
Dim firstfound As String
With ActiveSheet
Set DRng = Union( _
.Range("E7:AB33"), _
.Range("E45:AB71"), _
.Range("E82:AB108"), _
.Range("E119:AB145"), _
.Range("E156:AB182") _
)
End With
With DRng
Set c = .Find("1", LookIn:=xlValues)
If Not c Is Nothing Then
firstfound = c.Address
Do
' action
With c
.Font.Bold = SetBold
.Font.Color = vbBlack
.Value = "T"
With .Interior
.pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = RGB(0, 204, 153)
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End With
' find next
Set c = .FindNext(c)
If c Is Nothing Then
Exit Do
End If
Loop While c.Address <> firstfound
End If
End With
End Sub
FindNext 方法将在到达范围的末尾后回绕到范围的开头;因此比较第一个匹配的地址以结束循环。
【解决方案2】:
文件在我关闭时自动保存和保护。
忘记取消保护工作表。
现在它工作正常:)