简体   繁体   English

引用数组中的范围

[英]Referencing Ranges in Arrays

I have a code that turns cells white if they are gray, and stores that range in an array. 我有一个代码,如果单元格为灰色,则将其变为白色,并将该范围存储在数组中。 Then I check each range in that array to see whether it is empty and the pattern is solid (white). 然后,我检查该数组中的每个范围,以查看其是否为空以及模式是否为实心(白色)。 If it is, then I turn it a lighter shade of gray. 如果是,那么我将其变成浅灰色。 My code to test for this is currently 我目前要测试的代码

Dim Prev() As Range
'I also tried Prev() As Variant and have the same problem
Dim PrevCount As Long
Dim Counter As Long
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Target.Interior.Pattern = xlGray50 Then
    Target.Interior.Pattern = xlSolid
    PrevCount = PrevCount + 1
    ReDim Preserve Prev(1 To PrevCount)
    Set Prev(PrevCount) = Target
End If

For Counter = LBound(Prev) To UBound(Prev)
    If IsEmpty(Prev(Counter)) And Prev(Counter).Interior.Pattern = xlSolid  Then
        Prev(Counter).Interior.Pattern = xlGray25
    End If
Next

End Sub

No error occurs, but none of the ranges in the array that fulfill both criteria turn gray. 没有错误发生,但是同时满足两个条件的数组范围都没有变成灰色。 I know nothing is wrong with the array, because it works just fine if I just do 我知道数组没有什么问题,因为如果我这样做,它就可以正常工作

For Counter = LBound(Prev) To UBound(Prev)
    If Prev(Counter).Interior.Pattern = xlSolid  Then
        Prev(Counter).Interior.Pattern = xlGray25
    End If
Next

So the 所以

If IsEmpty(Prev(Counter)) 

Part does not work and I'm not sure why. 部分无法正常工作,我不确定为什么。

I suspect the IsEmpty is returning False always, because it will return True only if variable is not initialized . 我怀疑IsEmpty总是返回False ,因为只有在未初始化变量的情况下,它才会返回True

You need to do something else like a comparison to zero or empty string depending on your data. 您还需要执行其他操作,例如根据数据比较零或空字符串。 Best is you check this 最好是你检查一下

Prev(Counter) = 0

assuming you are dealing with numerical quantities. 假设您正在处理数字量。 That should work. 那应该工作。


Reviewing the new code there are two points here. 回顾新代码,这里有两点。 The Redim Preserve preserves all global data so it needs to be flushed empty (Redim to 0 elements) once your work is done. Redim Preserve保留所有全局数据,因此一旦完成工作,就需要将其清空为空(将Redim还​​原为0个元素)。

Secondly, you should try setting 其次,您应该尝试设置

Dim Test as Integer
Test = CInt(Prev(x).Value)
if Test = 0 Then .... so on and so forth

Do not use IsEmpty() rather use: 不要使用IsEmpty()而是使用:

If Prev(Counter) = "" And Prev(Counter).Interior.Pattern = xlSolid  Then

or 要么

If cStr(Prev(Counter).Value) = "" And Prev(Counter).Interior.Pattern = xlSolid  Then

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM