VBA - 创建空数组

时间:2017-03-24 17:15:37

标签: arrays vba

我有一个函数,它接受一个字符串数组并将每个字符串映射到Date实例。该函数归结为以下代码。

Private Function ParseDates(dates() As String) As Date()
  Dim res() As Date
  Dim i As Integer

  If UBound(dates) >= 0 Then
    ReDim res(UBound(dates)) As Date
  End If


  For i = LBound(dates) To UBound(dates)
    res(i) = #01/01/2000#
  Next i
  ParseDates = res
End Function

只要参数dates 非空,该函数就可以正常工作。如果dates为空res,则不会给出维度。因此,如果在循环中枚举结果,则返回的值不会被枚举,从而导致此函数的用户崩溃。

parsedDates = ParseDates(input) 
For i = 1 To UBound(parsedDates) ' Suscription out of range
  ...

当日期为空时,如何实例化并返回空数组?

如果您致电Split("","."),则会收到类型为String(0 to -1)的对象。我需要我的函数来返回Date(0 to -1)类型的对象,因为Date()不是实际的数组。

我尝试使用ReDim res(-1)会导致Subscript out of range错误。

4 个答案:

答案 0 :(得分:2)

我过去曾经使用过这样的东西。

Public Function IS_ARRAY_EMPTY(arrInput As Variant) As Boolean

Dim lngTemp As Long

On Error GoTo eHandle

lngTemp = UBound(arrInput)

IS_ARRAY_EMPTY = False

Exit Function

eHandle:
    IS_ARRAY_EMPTY = True

End Function

答案 1 :(得分:2)

这似乎可以解决问题:

Private Declare Function EmptyDateArray Lib "oleaut32" Alias "SafeArrayCreateVector" (Optional ByVal vt As VbVarType = vbDate, Optional ByVal lLow As Long = 0, Optional ByVal lCount As Long = 0) As Date()

Function emptyDate() as Date()
    emptyDate = EmptyDateArray()
End Function

基于用户 wgweto 对VBForums的this question的回答。

答案 2 :(得分:1)

您特别提到了调用代码需要迭代返回值并且迭代非维度数组的问题会引发错误。收藏不会有这个问题。一种可能性是重构代码,以便它返回一个集合(可能有也可能没有零元素):

Private Function ParseDates(dates() As String) As Collection
  Dim res As New Collection
  Dim i As Long

  For i = LBound(dates) To UBound(dates)
    res.Add #1/1/2000#
  Next i

  Set ParseDates = res
End Function

假设调用代码包含以下行:

Set C = ParseDates(dates)

即使C.Count = 0,以下循环也适用:

Dim d As Variant

For Each d In C
    'process d
Next d

答案 3 :(得分:-1)

试试这个:

Private Function ParseDates(dates() As String) As Date()
  Dim res() As Date
  Dim i As Integer
  Dim k%
  k=0
  If UBound(dates) >= 0 Then
    ReDim res(UBound(dates)) As Date
  End If


  For i = LBound(dates) To UBound(dates)
    if dates(i)<>"" then
       k=k+1      
    redim preserve res(k)
       end if
res(k) = #01/01/2000#
  Next i
    if k=0 then
     redim res(ubound(dates))
      end if
  ParseDates = res
End Function