单元格不为空,但显示为空

我有一些代码,我从网上拿来,它的工作原理。 但是,当我尝试增加范围时,有一些问题

此代码工作

Sub Test1() Dim strString$, x& strString = Range("B1").Value With Range("A1") .Font.ColorIndex = 1 For x = 1 To Len(.Text) - Len(strString) Step 1 If Mid(.Text, x, Len(strString)) = strString Then .Characters(x, Len(strString)).Font.ColorIndex = 5 Next x End With End Sub 

这没有

 Sub Test1() Dim strString$, x& strString = Range("B1").Value **With Range("A1:A2")** .Font.ColorIndex = 1 **For x = 1 To Len(.Text) - Len(strString) Step 1** If Mid(.Text, x, Len(strString)) = strString Then .Characters(x, Len(strString)).Font.ColorIndex = 5 Next x End With End Sub 

我相信我的单元格A1和A2不是空的。 但是,当我做它运行它在debugging模式下,它显示Len(.Text)为空。 但是,当我试图用这种方式做到这一点

这也可以

 Sub Test1() Dim strString$, x& strString = Range("B1").Value With Range("A2") .Font.ColorIndex = 1 For x = 1 To Len(.Text) - Len(strString) Step 1 If Mid(.Text, x, Len(strString)) = strString Then .Characters(x, Len(strString)).Font.ColorIndex = 5 Next x End With End Sub 

基于debugging器的错误在于这个代码

 Len(.Text) which is null 

你需要一个循环范围内的所有单元格,所以代码应该是这样的:

 Sub Test1() Dim rng As Range Dim strString$, x& strString = Range("B1").Value For Each rng In Range("A2:A3") rng.Font.ColorIndex = 1 For x = 1 To Len(rng.Text) - Len(strString) Step 1 If Mid(rng.Text, x, Len(strString)) = strString Then rng.Characters(x, Len(strString)).Font.ColorIndex = 5 Next x Next rng End Sub 

这是因为您不能在包含多个单元格的范围上调用.Text 。 您需要先遍历范围单元格,以便一次处理一个单元格。