VBA相当于Sizeof()?

时间:2012-09-07 15:46:04

标签: c++ vba sizeof

VBA中是否有等效的C++ sizeof函数?

唯一远程类似的函数似乎是数组上的UboundLBound运算符。

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

但这与C ++代码并不完全相同:

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

4 个答案:

答案 0 :(得分:3)

可以在VBA中使用的几个与指针相关的函数位于:http://support.microsoft.com/kb/199824没有明显的等效sizeof

对于数组,如果您暂时将数组延长一个项目然后将其缩小到所需大小,则可能会对VarPtr执行某些操作:

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

答案 1 :(得分:2)

会有 Len Function ,但是对于字符串,它将无法用作SizeOf,因为它将逐字检查字符串变量中包含的字符串的长度。

所以要检查一个int数组的字节大小:

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

立即窗口将显示: 8

答案 2 :(得分:0)

我意识到这太迟了,但是...您想要的是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

答案 3 :(得分:0)

VBA Reference Manual中所定义。

您可以使用LENLENB


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.

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.