Question

I have created a user defined type to contain some data that I will use to populate my form. I am utilizing an array of that user defined type, and I resize that array as I pull data from an off-site server.

In order to make my program easier to digest, I have started to split it into subroutines. However, when my program is initialized, I cannot tell when a particular array has been initialized, and so I cannot be certain that I can call a size function to see if the array is empty.

Is there a way to initialize an empty user type or detect a null user type? Currently, I am hard-coding it in and I would prefer a more elegant solution.

Was it helpful?

Solution

AFAIK, you cannot check whether user-defined type was initialized before it was sent as an argument to a procedure/function.

I am quoting this example from VBA help


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

The County field is initialized to some value, which you can use a base value. If the user sets this field explicitly, it means it holds some value & remains uninitialized, otherwise.

for e.g.

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

OTHER TIPS

In addition to isempty(array) solution -

If IsNull(array) then 

   msgbox "array is empty"

End If

Try:

dim v

if isempty(v) then
    msgbox "is empty"
end if
If myObjectVariable is Nothing

should work to detect if an object has been initialized.

Edit: "is nothing" DOES work, if it is an object variable:

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

If you need to check whether the whole dynamic array of custom types was initialized or not (not just particular element) in VBA, then this might not be possible directly (as none of the IsEmpty etc. functions works on custom types). However you might be able to easily restructure your program to return an array of custom types of size 0 to indicate that nothing was read/initialized.

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top