vba ReDim 语句是否使用空字符串初始化字符串数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1584263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 10:53:55  来源:igfitidea点击:

Does the ReDim statement initialise String Arrays with empty strings?

arraysvbavb6

提问by Kevin Boyd

Given the following statements in VBA:
Assume that val = 4and Option Base 0

鉴于 VBA 中的以下语句:
假设val = 4Option Base 0

Dim dataStr() As String
ReDim dataStr(val) 

Will the ReDim statement initialise the String array dataStr to 5 empty string elements(0 to 4).
What exactly will be the contents of the Array after the execution of the ReDim statement.

ReDim 语句是否会将字符串数组 dataStr 初始化为 5 个空字符串元素(0 到 4)。
执行 ReDim 语句后 Array 的内容究竟是什么。

采纳答案by Mike Woodhouse

Sub RedimStringArray()

Dim Val As Integer
Dim dataStr() As String
Dim idx As Long

    Val = 4

    ReDim dataStr(Val)

    For idx = LBound(dataStr) To UBound(dataStr)
        Debug.Print idx, """" & dataStr(idx); """", TypeName(dataStr(idx)), Len(dataStr(idx))
    Next

End Sub

gives me this:

给我这个:

 0            ""            String         0 
 1            ""            String         0 
 2            ""            String         0 
 3            ""            String         0 
 4            ""            String         0 

So I'd say that yes, ReDim re-initializes the array with empty strings.

所以我会说是的,ReDim 用空字符串重新初始化数组。

回答by MarkJ

You could just read the VB6 manual page on ReDim?

您可以阅读ReDim 上VB6 手册页吗?

When variables are initialized, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros

变量初始化时,变长字符串初始化为零长度字符串(""),固定长度字符串用零填充

回答by jtolle

Just to confirm the answer from Mike Woodhouse, see section 5.4.3.3 of the VBA Language Specification:

只是为了确认 Mike Woodhouse 的回答,请参阅 VBA 语言规范的第 5.4.3.3 节:

http://msdn.microsoft.com/en-us/library/dd361851%28PROT.10%29.aspx

http://msdn.microsoft.com/en-us/library/dd361851%28PROT.10%29.aspx

Each array in a <redim-statement> is resized according to the dimensions specified in its <bounds-list>. Each element in the array is reset to the default value for its data type, unless the word “preserve” is specified.

<redim-statement> 中的每个数组都根据其 <bounds-list> 中指定的维度调整大小。除非指定了“保留”一词,否则数组中的每个元素都将重置为其数据类型的默认值。