Excel的VBA - 初始化空的用户类型和空值检测
-
05-09-2019 - |
题
我已经创建了一个用户定义的类型为包含一些数据,我将用于填充我的形式。我利用该用户定义类型的阵列,并且我调整该阵列我拉从场外服务器数据。
为了使我的程序更容易消化,我已经开始将其分割成子程序。然而,我的程序被初始化时,我不能告诉当一个特定的阵列已经被初始化,所以我不能肯定,我可以调用一个函数的大小,看是否数组为空。
有一种方法来初始化一个空的用户类型或检测一个零用户类型?目前,我硬编码的,我希望能有一个更好的解决方案。
解决方案
AFAIK,你不能检查,然后将其作为参数传递给一个过程/功能发送的用户定义类型是否被初始化。
我引用从VBA帮助这个例子
Type StateData
CityCode(1 To 100) As Integer ' Declare a static array.
County As String * 30
End Type
在县字段被初始化为某一值,其可以使用一个基值。 如果用户明确地设置该字段,则意味着它拥有一些值保持未初始化,否则
有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
其他提示
在除的isEmpty(阵列)溶液 -
If IsNull(array) then
msgbox "array is empty"
End If
尝试:
dim v
if isempty(v) then
msgbox "is empty"
end if
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
如果您需要检查自定义类型的全动态数组是否初始化或不(不只是特定元素)在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
不隶属于 StackOverflow