1

我创建了一个用户定义的类型来包含一些我将用来填充我的表单的数据。我正在使用该用户定义类型的数组,并在从异地服务器提取数据时调整该数组的大小。

为了让我的程序更容易消化,我开始把它拆分成子程序。但是,当我的程序被初始化时,我无法判断某个特定数组何时被初始化,因此我无法确定是否可以调用 size 函数来查看数组是否为空。

有没有办法初始化空用户类型或检测空用户类型?目前,我正在对其进行硬编码,我更喜欢更优雅的解决方案。

4

5 回答 5

5

除了 isempty(array) 解决方案 -

If IsNull(array) then 

   msgbox "array is empty"

End If
于 2009-04-06T15:23:58.677 回答
2

AFAIK,您无法检查用户定义类型在作为参数发送给过程/函数之前是否已初始化。

我从 VBA 帮助中引用了这个例子


Type StateData
    CityCode(1 To 100) As Integer     ' Declare a static array.
    County As String * 30
End Type

County 字段被初始化为某个值,您可以使用该值作为基值。如果用户明确设置此字段,则意味着它拥有一些值并保持未初始化,否则。

例如

Sub main()
    Dim example As StateData
    MsgBox IsInitialized(example)

    Dim example2 As StateData
    example2.County = "LA"
    MsgBox IsInitialized(example2)
End Sub
Function IsInitialized(arg As StateData) As Boolean
    Dim initCounty As String * 30
    IsInitialized = (arg.County <> initCounty)
End Function
于 2009-04-06T16:03:08.817 回答
1

尝试:

dim v

if isempty(v) then
    msgbox "is empty"
end if
于 2009-04-06T15:05:07.847 回答
0
If myObjectVariable is Nothing

应该可以检测对象是否已初始化。

编辑:“什么都不是”确实有效,如果它是一个对象变量:

Dim blah As Object
If blah Is Nothing Then
    MsgBox "blah is nothing!"
End If

Dim foo as variant
If IsEmpty(foo) Then
    MsgBox "foo is empty!"
End If
于 2009-04-06T14:53:09.747 回答
0

如果您需要检查自定义类型的整个动态数组是否已在 VBA 中初始化(不仅仅是特定元素),那么这可能无法直接进行(因为 IsEmpty 等函数均不适用于自定义类型)。但是,您可能能够轻松地重组程序以返回大小为 0 的自定义类型的数组,以指示没有读取/初始化任何内容。

Private Function doStuff() As customType()
    Dim result() As customType

    ' immediately size it to 0 and assing it as result
    ReDim result(0)
    doStuff = vysledek

    ' do real stuff, ... premature "Exit Function" will return an array of size 0
    ' possibly return initialized values
End Function

' then you can all
If (UBound(tabulky) = 0) Then
    MsgBox "Nope, it is not initialized."
End If
于 2014-03-06T17:08:26.763 回答