如果数组已由Range指定,则LBound和Ubound冲突

aru*_*roy 1 vbscript excel vba excel-vba

    height = objExcel1.Application.WorksheetFunction.CountA(ob3.Columns(1))
    'MsgBox(height)
    ReDim dataArray(height - 2, 0) ' -1 for 0 index, -1 for the first row as header row, excluded
    str = ""
    dataArray = ob3.Range(ob3.Cells(2, 1),ob3.Cells(height, 1)).Value
    Set d = CreateObject("scripting.dictionary")
    'MsgBox(LBound(DeletArr) & ":" & UBound(DeletArr))
    For i = LBound(DeletArr) To UBound(DeletArr)
        If Not d.exists(DeletArr(i)) Then
            d(DeletArr(i)) =  0
        End If
    Next
    MsgBox(LBound(dataArray,1) & ":" & UBound(dataArray,1))
    For i = LBound(dataArray, 1)  To UBound(dataArray, 1) - 1

        If d.exists(dataArray(i, 1)) Then

            str = str & (i+1) & ":" & (i+1) & ","
            'ob3.Range(i & ":" & i).Delete

        Else
            'found = False
        End If

    Next
Run Code Online (Sandbox Code Playgroud)

VBScript数组基于0.但是为什么LBound(dataArray,1)给出下标是1,为什么不给0?Ubound给出数字 - 我对此感到困惑的是它是数组的最后一个下标还是大小?

谢谢,

bon*_*igo 5

默认情况下,VBA数组的下标/索引从0开始(这称为数组的下限)并运行到您在Dim语句中指定的数字(这称为数组的上限).如果您希望数组索引号从1开始,请在模块顶部包含以下语句.

Option Base 1

在此输入图像描述

但是,当Range使用该Transpose方法对象填充数组时,即使您处于默认Zero baed模式,数组下限也会设置为1 .因此数组变为1.

例如,使用Transpose方法添加以下数据.

Array(1) = "Hola"
Array(2) = "Bonjour"
Array(3) = "Hello"
Array(4) = "Wei"
Run Code Online (Sandbox Code Playgroud)

好的是这个数组UBound告诉你元素(4)的数量= UBound.与基于零的情况不同,则元素数= Ubound + 1.

UBound(Array) --> 4
LBound(Array) --> 1
Run Code Online (Sandbox Code Playgroud)

在当前基于1的场景中,Ubound指的是元素总数.因此,在这种情况下,您需要修改代码以跟踪数组中的数据LBound,UBound以避免数据丢失.

并顺便说一下,通过添加Option Base 0不停止数组的Transpose方法为1 .这是我的第一个评论.