如果数组为空,请不要进入此循环

时间:2014-09-25 19:40:50

标签: vba excel-vba excel

现在我使用的方法是为了避免进入for循环,循环通过当前为空的数组如下:

如果len(join(array,“”)> 0则    for i = 1 to ubound(array)        码    下一个 结束如果

但这不是开玩笑,我刚刚使用了那行代码,如果len(join(array,“”)> 0然后导致删除数组并且它连续5次崩溃我的程序。我知道这听起来很难相信,但这里是一个屏幕截图enter image description here

由于某种原因,代码len(join(array,“”)> 0会破坏variables2数组。这是一个屏幕截图,显示变量数组在我转到错误代码之前显然已满:{ {0}}所以现在我正在尝试使用我尝试的其他代码:

如果不是isempty(数组)那么

但那不起作用。有什么想法吗?

If Len(Join(greek_act, "")) > 0 Then
        For i = 1 To UBound(greek_act)
            For j = 1 To UBound(variables2)
                If greek_act(i) = variables2(j) Then
                variables2(j) = ""
                Exit For
                End If
            Next
        Next
    variables2 = remove_blanks(variables2)
    End If

    'variables2 array is full

    If Len(Join(greek_letters, "")) > 0 Then

    'variables2 array gets destroyed and program crashes here.

            For i = 1 To UBound(greek_letters)
                rightres1 = Replace(rightres1, greek_letters(i), variables2(i))
            Next

    End If

3 个答案:

答案 0 :(得分:0)

没关系,我决定继续使用以下解决方案,因为该程序似乎暂时起作用

On Error Resume Next

        For i = 1 To UBound(greek_letters)
            rightres1 = Replace(rightres1, greek_letters(i), variables2(i))
        Next



On Error GoTo 0``

答案 1 :(得分:0)

要使加入()技术可靠地运作,您必须完成调光/重新调整过程:

Sub dural()
    Dim greek_ary(1 To 3) As String
    s = Join(greek_ary, "")
    MsgBox Len(s)
End Sub

如果没有填充数组, Len 将报告 0

答案 2 :(得分:0)

由于这是一个常见的测试,我喜欢使用这样的可重用函数:

Function IsArrayEmpty(anArray As Variant)
    Dim i As Integer

    On Error Resume Next
        i = UBound(anArray, 1)
    If Err.Number = 0 Then
        IsVarArrayEmpty = False
    Else
        IsVarArrayEmpty = True
    End If
End Function

现在在您的主要Sub中执行此操作:

If Not IsArrayEmpty(greek_act) Then
    For i = 1 To UBound(greek_act)
        For j = 1 To UBound(variables2)
            If greek_act(i) = variables2(j) Then
                variables2(j) = ""
                Exit For
            End If
        Next
    Next
    variables2 = remove_blanks(variables2)
End If
相关问题