简体   繁体   English

Redim Preserve 内的 UBound 抛出“下标超出范围”

[英]UBound inside Redim Preserve throws “Subscript out of range”

I want to use a dynamic array containing arbitrary number of strings.我想使用包含任意数量的字符串的动态数组。 The array is filled by if... then logic instead of a loop.数组由if... then逻辑而不是循环填充。 I keep getting Subscript out of range error:我不断收到Subscript out of range错误:

Dim Files() As String

If True Then
    ReDim Preserve Files(UBound(Files) + 1) ' Throws "Subscript out of range" error
    Files(UBound(Files)) = "foo.pdf"
End If

If True Then
    ReDim Preserve Files(UBound(Files) + 1)
    Files(UBound(Files)) = "bar.txt"
End If

If True Then
    ReDim Preserve Files(UBound(Files) + 1)
    Files(UBound(Files)) = "baz.jpg"
End If

I have a function declared like this:我有一个 function 声明如下:

Function SendFiles(Files() As String)

I want to get rid of this error without using variants if possible .如果可能的话,我想在不使用变体的情况下摆脱这个错误。 I can rewrite the code but I cannot use a loop.我可以重写代码,但我不能使用循环。

Your array is not initialized at the start, and you can't Redim Preserve an uninitialzed array.您的数组在开始时未初始化,您无法Redim Preserve未初始化的数组。

If you want a string array to hold a variable amount of items, possibly zero, you can start with initializing it to a zero-length array using Split :如果您希望字符串数组包含可变数量的项目,可能为零,您可以从使用Split将其初始化为零长度数组开始:

Files = Split(vbNullString)

You could also allocate a large enough array and resize to used size afterwards.您还可以分配一个足够大的数组,然后将大小调整为使用的大小。 That way you have only 1 resize.这样你只有 1 个调整大小。 Something like this:像这样的东西:

Dim Files(1000) As String, i as long

If True Then
    Files(i) = "foo.pdf": i = i+1
End If

If True Then
    Files(i) = "bar.txt": i = i+1
End If

If True Then
    Files(i) = "baz.jpg": i = i+1
End If

redim preserve Files(i-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM