gpt4 book ai didi

vba - 使用 Redim 设置数组数据类型

转载 作者:行者123 更新时间:2023-12-04 19:59:22 25 4
gpt4 key购买 nike

当我第一次创建数组时,我知道最好将数据类型设置为默认 Variant类型很慢,否则最好在 VBA 中避免

我注意到

Redim t(1 To 10) As String

似乎具有相同的效果
Dim t() As String
Redim t(1 To 10)

但我想知道;第一个选项是否首先转换 t()Variant然后转换为 String ,双写浪费内存?
或者,由于两条线,第二个选项实际上更慢。当我 Dim 时,内存中实际发生了什么一个没有指定大小的数组?

当然
Dim t(1 To 10) As String

被认为是最有效的,但我需要 Redim Preserve反正以后会这样,所以不能那样做。

最佳答案

What actually happens in memory when I Dim an array without specifying its size?



你得到一个未初始化的、动态大小的数组:VBA 在内存中“保留一个点”。确切的工作原理是只有 Microsoft 才能回答的内部管道 - 除非您可以对 P-Code 进行逆向工程(假设您可以首先提取已编译的 P-Code)。

两个 DimReDim可以充当声明性语句 - 并不意味着它们都应该 - 来自 MSDN (强调我的):

The ReDim statement acts as a declarative statement if the variable it declares doesn't exist at module level or procedure level. If another variable with the same name is created later, even in a wider scope, ReDim will refer to the later variable and won't necessarily cause a compilation error, even if Option Explicit is in effect. To avoid such conflicts, ReDim should not be used as a declarative statement, but simply for redimensioning arrays.



当你说:

Or is the second option actually slower because of the 2 lines.



你忘了 Dim不是可执行语句(不能中断 Dim 语句)。 ReDim虽然是。因此,就运行时而言,这两个“选项”基本上是相同的,除了第一个( ReDim 用作声明性语句)违反最佳实践。

因此,如果您需要动态数组,请使用 Dim 声明动态数组。 :
Dim foo() As String

然后当你需要调整它的大小时,使用 ReDim要做到这一点:
ReDim foo(1 To bar)

根据经验,您不必担心 DimReDim 更有效,或者如果它是相反的方式 - 如果您的代码有性能问题,那么有 99.9999999997% 的可能性是您的算法问题,而不是 VBA 如何实现变量和数组分配。

关于vba - 使用 Redim 设置数组数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44310473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com