VBA Equivalent of Sizeof()?

半城伤御伤魂 提交于 2019-12-11 03:46:10

问题


Is there an equivalent of the C++ sizeof function in VBA?

The only remotely similar functions seem to be the Ubound and LBound operators on arrays.

Dim arr(1 to 4) as integer
MsgBox Ubound(arr)

But this is not really the same thing as the C++ code:

int arr[10];
std::cout << sizeof(std::string) << "\t" << sizeof(arr);

回答1:


The few pointer-related functions that can be used in VBA are at: http://support.microsoft.com/kb/199824 No obvious equivalent of sizeof though

For an array, you could potentially do something with VarPtr if you temporarily made the array one item longer and then shrank it back to the desired size:

Sub foo()

Dim arr() As Integer 
Dim i As Integer

ReDim arr(1 To 5)
arr(1) = 12
arr(2) = 456
arr(3) = -41
arr(4) = 17

Debug.Print VarPtr(arr(1)) & "; " & VarPtr(arr(5)) & "; " & VarPtr(arr(5)) - VarPtr(arr(1))

ReDim Preserve arr(1 To 4)

End Sub



回答2:


There would be the Len Function but with strings it will not work as SizeOf because it will literally check the length of the string contained in a string variable.

So to check the byte size of an array of ints:

Dim arr(1 To 4) As Integer
Debug.Print (UBound(arr) - LBound(arr) + 1) * Len(arr(LBound(arr)))

Immediate window will show: 8




回答3:


I realise this is super late, but... What you want is LenB()

Public Type RECT
    Left As Long
    Top As Long
    Right As Long
    Bottom As Long
End Type

Debug.Print LenB("a") '==>2 i.e. ["a",0&]

Dim r as RECT
debug.print LenB(r) '==>16 i.e. 4 bytes for each long



回答4:


As defined in VBA Reference Manual.

You can use LEN or LENB


Example of LEN

Type CustomerRecord    ' Define user-defined type.
    ID As Integer    ' Place this definition in a 
    Name As String * 10    ' standard module.
    Address As String * 30
End Type

Dim Customer As CustomerRecord    ' Declare variables.
Dim MyInt As Integer, MyCur As Currency
Dim MyString, MyLen
MyString = "Hello World"    ' Initialize variable.
MyLen = Len(MyInt)    ' Returns 2.
MyLen = Len(Customer)    ' Returns 42.
MyLen = Len(MyString)    ' Returns 11.
MyLen = Len(MyCur)    ' Returns 8.

Example of LENB

Function LenMbcs (ByVal str as String)
    LenMbcs = LenB(StrConv(str, vbFromUnicode))
End Function

Dim MyString, MyLen
MyString = "ABc"
' Where "A" and "B" are DBCS and "c" is SBCS.
MyLen = Len(MyString)
' Returns 3 - 3 characters in the string.
MyLen = LenB(MyString)
' Returns 6 - 6 bytes used for Unicode.
MyLen = LenMbcs(MyString)
' Returns 5 - 5 bytes used for ANSI.


来源:https://stackoverflow.com/questions/12321404/vba-equivalent-of-sizeof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!