我试图遍历不同的范围,用其他值/格式将值替换为“ 1”的单元格。
如果我一一使用范围,则效果很好。但是,当我尝试组合不同的范围并遍历数组时,在.Pattern部分收到了应用程序定义的运行时错误。
我读过它与没有定义工作表有关,但是我不确定如何在此设置中正确地完成工作。
我已经尝试过:
cell.select之前带有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
答案 0 :(得分:0)
文件自动保存并在我关闭时受到保护。 忘记取消保护纸张。 现在可以正常工作了:)
答案 1 :(得分:0)
建议:与其遍历每个范围中的每个单元格,您只需构建一个包含所有范围的范围对象,然后搜索该范围内的匹配单元格即可:
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
方法将在到达范围的末尾时环绕到范围的开头;因此比较第一个匹配的地址以结束循环。