Excel VBA错误

我正在尝试使用VBA自动更改包含pipe道字符“|”的单元格的颜色。

当检测到时,我想代码去除pipe道字符“|” 并将单元格颜色更改为灰色。 代码不起作用,如下所示:

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”: 对象variables或块variables未设置

代码在这里失败:

循环虽然不是c是什么和c.Address <> firstAddress

崩溃后,我的debugging手表具有以下值:

expression式firstAddress" = $AG$37 (这是合并和居中范围内的第一个单元格 – 一个需求)

expression式c.Address =对象variables或未设置块variables

expression式c.Value =对象variables或未设置块variables

我将不胜感激任何帮助。

谢谢!

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)find所有的单元格,其第一个字符是pipe道字符“|”,2)删除pipe道字符“|”,3)对单元格灰色。

再次感谢达伦和约翰!

jmseiver

你必须testingc是不是在一个不同时(尽pipe隐含地)假设它不是什么都不是的情况下。 像这样(未经testing):

 With Sheets("DATASHEET").Range("AG1:BG53") Set c = .Find("|", LookIn:=xlValues) If Not c Is Nothing Then firstAddress = c.Address Do c.Value = "" Set c = .FindNext(c) If c is Nothing Then Exit Do Loop While c.Address <> firstAddress End If End With 

问题在于与大多数编程语言不同,VBA不会使逻辑运算符短路。 即使A是假的, AB总是A and B评估。 因此,您有时需要在VBA中以更全面的方式编写代码。

可以使用Excel查找和replace格式进行简化:

 Application.ReplaceFormat.Clear ' optional Application.ReplaceFormat.Interior.ColorIndex = 15 ' set the replacement format [DATASHEET!AG1:BG53].Replace "|", "", LookAt:=xlPart, ReplaceFormat:=True 

但是,这就像你更新的代码将取代包含 |所有单元格 。

仅查找 | 开头的单元格 ,您可以将代码中的查找条件replace为:

 Set c = .Find("|*", , LookIn:=xlValues, LookAt:=xlWhole)