【发布时间】:2017-04-15 08:48:40
【问题描述】:
我正在尝试使用 VBA 自动更改包含管道字符“|”的单元格的颜色。
当检测到时,我希望代码删除管道字符“|”并将单元格颜色更改为灰色。该代码不起作用,如下所列:
With Sheets("DATASHEET").Range("AG1:BG53")
Set c = .Find("|", LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
Do
c.Value = ""
c.Pattern = xlSolid
c.PatternColorIndex = xlAutomatic
c.ThemeColor = xlThemeColorDark1
c.TintAndShade = -0.249977111117893
c.PatternTintAndShade = 0
Loop While Not c Is Nothing And c.Address <> firstAddress
End If
End With
当我运行 VBA 时,我收到以下错误:
运行时错误“91”: 对象变量或未设置块变量
这里的代码失败了:
循环 While Not c Is Nothing And c.Address firstAddress
崩溃后,我的调试手表具有以下值:
表达式firstAddress" = $AG$37(这是范围内第一个合并并居中的单元格 - 要求)
表达式 c.Address = 对象变量或未设置块变量
表达式 c.Value = 对象变量或未设置块变量
我将不胜感激。
谢谢!
jmseiver
更新:
此代码有效,谢谢 Darren!
With Sheets("DATASHEET").Range("AG1:BG53")
Set c = .Find("|", LookIn:=xlValues)
If Not c Is Nothing Then
Do
c.Value = ""
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.249977111117893
.PatternTintAndShade = 0
End With
Set c = .FindNext(c)
Loop While Not c Is Nothing
End If
End With
这段代码没有:
With Sheets("DATASHEET").Range("AG1:BG53")
Set c = .Find("|", LookIn:=xlValues)
If Not c Is Nothing Then
Do
c.Value = ""
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.249977111117893
.PatternTintAndShade = 0
End With
Set c = .FindNext(c)
Loop While Not c Is Nothing
End If
End With
更改单元格颜色是例程的目的。附加的 With - End With 不起作用。
它不会爆炸,只是不会改变单元格的颜色。
?
感谢大家到目前为止的时间!
jmseiver
更新 2:
此代码有效!
'color any cell with updated data to gray
With Sheets("DATASHEET").Range("AG1:BG53")
Set c = .Find("|", LookIn:=xlValues)
If Not c Is Nothing Then
Do
c.Replace What:="|", Replacement:=""
c.Interior.ColorIndex = 15
Set c = .FindNext(c)
Loop While Not c Is Nothing
End If
End With
总而言之,这段代码的目的是 1) 找到第一个字符是管道字符“|”的所有单元格,2) 删除管道字符“|”,以及 3) 将单元格着色为灰色。
再次感谢达伦和约翰!
jmseiver
【问题讨论】:
标签: excel vba with-statement