当范围只包含一个值

时间:2016-03-04 19:30:05

标签: excel vba excel-vba

我有一个函数用于返回一个由单列数据列表创建的数组。我一直把这个函数的返回值用作伪全局变量(LINENAMES_ARRAY),我将其传递给许多函数。除了对If Len(Join(LINENAMES_ARRAY)) = 0 Then进行检查或使用For Each语句进行检查之外的其他功能。这是代码:

  Function LINENAMES_ARRAY() As Variant
  'returns an array of all items in the main sheet linenames column
      LINENAMES_ARRAY = Application.Transpose(MAIN.Range( _
      MAIN.Cells(MAIN_HEAD_COUNT + 1, MAIN_LINENAMES_COLUMN), _
      MAIN.Cells(LINENAMES_COUNT + 1, MAIN_LINENAMES_COLUMN)))
  End Function

我最近偶然发现了一个你在使用这个工作簿进行新项目的时候看不到它的问题,如果这个数组恰好只有1个元素,一切都失败了显然,在这种情况下,这会返回一个值,因此Join()也会失败For Each __ in LINENAMES_ARRAY。为什么不将它视为1x1数组而不是自由值?我已经开始通过重写调用它的函数来缓解这个问题,检查它是否是一个数组,然后再做一些其他的过程。比如:

For j = 1 To LINENAMES_COUNT
    LINES_BOX.AddItem lineNames(j)
Next j

更改为:

If Not IsArray(LINENAMES_ARRAY) Then
     myListBox.AddItem CStr(LINENAMES_ARRAY)
Else
    For j = 1 To LINENAMES_COUNT
       LINES_BOX.AddItem LINENAMES_ARRAY(j)
    Next j
End If

然而,这会变得混乱,并且在我的代码中添加了许多额外的检查,我希望在LINENAMES_ARRAY函数中处理这些检查。有没有办法返回1x1阵列?或任何其他解决方法?

1 个答案:

答案 0 :(得分:6)

如果您将数组创建为单个元素数组并以数组方式填充它,则该数组可以包含单个元素。

Option Explicit

Dim MAIN_HEAD_COUNT As Long
Dim LINENAMES_COUNT As Long
Dim MAIN_LINENAMES_COLUMN As Long
Dim MAIN As Worksheet

Sub stuff()
    Dim arr As Variant
    Set MAIN = Worksheets("Sheet1")
    MAIN_LINENAMES_COLUMN = 2
    MAIN_HEAD_COUNT = 2
    LINENAMES_COUNT = 2

    arr = LINENAMES_ARRAY()
    Debug.Print IsArray(arr)
    Debug.Print LBound(arr) & ":" & UBound(arr)
End Sub

Function LINENAMES_ARRAY() As Variant
    Dim a As Long, tmp() As Variant
    ReDim tmp(0 To LINENAMES_COUNT - MAIN_HEAD_COUNT)
    For a = 0 To LINENAMES_COUNT - MAIN_HEAD_COUNT
        tmp(a) = MAIN.Range(MAIN.Cells(MAIN_HEAD_COUNT + 1, MAIN_LINENAMES_COLUMN), _
                            MAIN.Cells(LINENAMES_COUNT + 1, MAIN_LINENAMES_COLUMN)).Cells(a).Value2
    Next a
    'returns an array of all items in the main sheet linenames column
    LINENAMES_ARRAY = tmp
End Function

VBE' Immediate window的结果:

True
0:0