【问题标题】:Excel VBA Array from Range Starting at -1 rather than 0范围从-1而不是0开始的Excel VBA数组
【发布时间】:2015-01-10 16:04:11
【问题描述】:

我正在使用 Excel 中的 VBA。我希望用户能够选择一组垂直的连续单元格并将这些单元格的值放入一个数组中。下面的代码做到了这一点,但我不知道为什么 Debug.Print DatArr(0) 打印所选区域上方一个单元格的值。我做错了什么?

Option Explicit
Option Base 0

Sub reconcile()
Dim DatArr As Range
Dim AuxDat As Range
Dim StartCellRange As String
Dim CellCnt As Integer


    Set DatArr = Application.InputBox("Select a contiguous range of cells.", "SelectARAnge Demo",   Selection.Address, , , , , 8)
    CellCnt = DatArr.Count


    DatArr.Select

    Selection.Offset(0, -1).Select


    Set AuxDat = Selection
    Debug.Print AuxDat.Count
    Debug.Print AuxDat(0)
    Debug.Print DatArr(0)
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您需要参考AuxDatDatArr 他们所代表的范围

    ' First cell in AuxDat.
    Debug.Print AuxDat.Cells(1, 1).Value
    
    ' First cell in DatArr.
    Debug.Print DatArr.Cells(1, 1).Value
    

    通过访问,例如AuxDat(x),将允许任何值,即使它超出了您选择的范围(只要它符合 Excel 的范围)。例如(使用您的代码),选择范围$B$5:$B$7

    Debug.Print AuxDat(-1) ' This is allowed and will print A3.
    Debug.Print AuxDat(5) ' This is allowed and will print A9.
    

    【讨论】:

      【解决方案2】:

      这是因为 Option Base 语句会影响 数组 而不是 范围。
      所以您在 之前查看一个单元格 范围的开始。

      【讨论】:

      • 为了清楚起见,使用的 Option Base 设置不会影响 OP 代码中的输出。
      • @JasonFaulkner .........你是绝对正确的!!............ Option Base 可以完全省略,因为发布的代码没有生成数组。
      • 不仅如此,Option Base 仅影响未指定下限的声明数组。 Range.Value 数组将始终以 1 为基数,无论选项基数如何。
      【解决方案3】:

      编辑您的代码:

      Option Explicit
      
      Sub reconcile()
      Dim DatArr As Range
      Dim AuxDat As Range
      Dim CellCnt As Integer
      
      Set DatArr = _
          Application.InputBox( _
            "Select a contiguous range of cells.", _
            "SelectARAnge Demo", _
            Selection.Address, , , , , 8)
      
      CellCnt = DatArr.Count
      
      If DatArr.Columns(1).Column > 1 Then  '<<small error trap in case the user selects column A
          Set AuxDat = DatArr.Offset.Offset(0, -1)
      End If
      
      Debug.Print AuxDat.Count
      Debug.Print AuxDat(1).Value
      Debug.Print DatArr(1).Value
      End Sub
      

      正如 Gary 的学生所说,范围是从 1 开始索引的单元格集合。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-16
        • 2023-03-30
        • 2020-09-18
        • 2014-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多