VBA - 创建空数组

问题描述 投票:0回答:4

我有一个函数,它接受一个字符串数组并将每个字符串映射到一个

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
错误。

arrays vba
4个回答
5
投票

这似乎可以解决问题:

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上针对这个问题的回答。


3
投票

我过去用过类似的东西。

Public Function IsArrayEmpty(arrInput As Variant) As Boolean   
    Dim lngTemp As Long

    On Error GoTo eHandle
    lngTemp = UBound(arrInput)
    IsArrayEmpty = False
    Exit Function

eHandle:
    IsArrayEmpty = True
End Function

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

0
投票

试试这个:

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
© www.soinside.com 2019 - 2024. All rights reserved.