【问题标题】:LBound and Ubound conflicts in case of array which has been assigned by the Range如果数组已由 Range 分配,则 LBound 和 Ubound 冲突
【发布时间】:2012-12-11 14:12:26
【问题描述】:

代码

    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

VBScript 数组是基于 0 的。但是为什么LBound(dataArray,1) 给出的起始下标是1,为什么不是0? Ubound 给出了数字 - 我有点困惑是数组的最后一个下标还是大小?

谢谢,

【问题讨论】:

  • 圣诞快乐!如果您希望数组从零开始,请添加option base 0 :) 让我为您提供一个测试代码。
  • @bonCodigo 圣诞快乐!祝你,希望你和你的家人享受一整天!
  • @bonCodigo 好的!我相信你的话!但是 Ubound() 返回的数字是它的最后一个下标还是该数组中的元素总数?也请确认。由于这个概念,我的脚本会导致数据丢失!!
  • 你能告诉我你在哪里有丢失数据的问题吗?如果您参考我们提供给您的大多数示例代码,则使用Transpose 方法从 Range 对象填充数组。
  • @bonCodigo 我基本上受过 C、C++、java、oracle 的教育——在哪个平台上我从未见过这样的场景!但它的好运气数据丢失帮助我知道了这个因素!现在我需要真正去每个脚本,需要检查哪些是按范围分配的,需要设置循环不是lboundas 0 而是1Ubound 不是ubound-1 而是@987654332 @!!!呵呵,上帝救救我:-)

标签: excel vbscript vba


【解决方案1】:

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

Option Base 1

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

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

Array(1) = "Hola"
Array(2) = "Bonjour"
Array(3) = "Hello"
Array(4) = "Wei"

好消息是这个数组UBound 告诉你元素的数量 (4) = UBound。与从零开始不同,元素数 = Ubound + 1。

UBound(Array) --> 4
LBound(Array) --> 1

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

顺便说一句,通过添加 Option Base 0 并不会阻止数组被基于 Transpose 方法的 1 提及。这使我的第一条评论无效。

【讨论】:

  • 只是为了确认一件事,Arraylist 和 Dic.keys 和 dic.items 是基于 0 的,对吗?我知道,仍然确认相同!
  • 将数组设为基于0 或基于1 的语法是什么? :-)
  • Dictionary.keys 返回一个zero based 数组,这就是为什么当您执行Array = D.Keys 时会得到基于0 的数组。 Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.
  • 如果你想FORCE你所有的数组都是基于1的(根据你的场景最好的选择)然后在代码模块中的Optoin Explicit之后添加Option Base 1
  • 感谢您的大量解释!我正在寻找的另一个信息是 - 我可以将ob4.Range("A1") 写成("1:1") 吗?请确认。如果可能的话,我会很高兴:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
相关资源
最近更新 更多