使用VBA循环遍历数组

4

我很久以来一直在寻找答案,但是无论我尝试什么,都会遇到不同的错误。

我有一段可用的代码:

Dim arkwyn As Variant
arkwyn = Array(1, 2, 3, "stats-obl")

For Each x In arkwyn
....
Next

但我需要在更复杂的工作表中使用类似的方法。此外,它需要快速执行,因为它将成为更复杂的更新过程的一部分,该过程不断跟踪工作表中的许多字段。

您能否请看一下并帮助我正确地完成它?

Private Function RowNo(ByVal text1 As String)
    RowNo = Columns(2).Find(text1, Lookat:=xlWhole).Row
End Function

Dim t1r As Variant 
Dim t1 As Integer

t1r = Array("1.2", "1.3", "1.4", "1.5", "1.6.2", "1.8", "1.9", "1.13.1.1", _
"1.13.1.2", "1.13.2")

For t1 = LBound(t1r) To UBound(t1r)
    Select Case UCase(Cells(RowNo(t1), 3).Value)
        Case "x"
            Rows(RowNo(t1) + 1).Hidden = False
        Case Else
            Rows(RowNo(t1) + 1).Hidden = True
    End Select
Next t1

感谢您的回答,我尝试进一步实现并创建了以下内容:
Dim ColAn As Long           
ColAn = 4
Dim YtQ1Ar As Variant       
Dim Y1q, rY1q As Long        


YtQ1Ar = Array("1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.7.1", "1.7.2", _
"1.7.3", "1.7.4", "1.7.5", "1.7.6", "1.7.7", "1.7.8", "1.7.9", "1.7.10", "1.7.11")

    For Y1q = LBound(YtQ1Ar) To UBound(YtQ1Ar)
        rY1q = RowNo(YtQ1Ar(Y1q))
        Rows(rY1q).Hidden = (UCase(Cells(RowNo("1."), ColAn).Value) <> "TAK")
    Next Y1q

这个想法是,单元格的值应该显示特定数量的行。但我一直得到“运行时错误91:对象变量或 With 块变量未设置”的提示。我在哪里犯了错?


你的代码出现了什么错误? - Tim Williams
运行时错误91,对象变量未设置。 - torin
1个回答

3

编辑 - 修正了类型和Rowno函数

'Return the row for a given value, or zero if not found
Private Function RowNo(ByVal text1 As String) As Long
    Dim f As Range
    Set f = Columns(2).Find(text1, Lookat:=xlWhole)
    If Not f Is Nothing Then
        RowNo = f.Row
    Else
        RowNo = 0
    End If
End Function

'...
Dim t1r As Variant 
Dim t1 As Long, r As Long

t1r = Array("1.2", "1.3", "1.4", "1.5", "1.6.2", "1.8", "1.9", _
             "1.13.1.1", "1.13.1.2", "1.13.2")

For t1 = LBound(t1r) To UBound(t1r)
    r = RowNo(t1r(t1))
    If r > 0 Then
        Rows(r + 1).Hidden = (UCase(Cells(r, 3).Value)<>"X")
    Else
        Debug.Print "'" & t1r(t1) & "' was not found!"
    End If
Next t1
'...

我认为那个底部需要用Sub包装起来。 - shg
是的 - 我假设OP知道这一点,因为他们在没有Sub/End sub的情况下发布了。 - Tim Williams
是的,这是不同的Sub。我在某个地方读到过,应该尽量避免使用Variant变量,你能告诉我在这种情况下是否足够吗?还有一个关于代码的问题。如果我需要在电子表格中取消隐藏许多行(使用RowNo函数找到),我应该如何重写代码? - torin
1
t1r 必须是 Variant 类型,因为 Array 函数返回的就是这种类型。t1 应该声明为 Long 类型,因为 Excel 中的行数超过了 Integer 类型所能处理的范围,而 RowNo 函数应该在签名末尾包含 As Long 而不是默认为 Variant 类型。 - shg
"Dim t1 As Integer, r" 这段代码是否意味着 r 也是一个已声明的变量?这是否与 "Dim t1, r as Integer" 的意思相同? - torin
有一个变量r,但那只是我有点懒 - 应该是Dim t1 As Long, r As Long。正如@shg所指出的,整数在Excel中的最大行数可能会溢出,但无论如何,始终使用Long代替Integer更有效率:请参见https://dev59.com/hV8d5IYBdhLWcg3wzU6r。 - Tim Williams

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接