gpt4 book ai didi

arrays - vba Excel 2010 : convert string array into int array

转载 作者:行者123 更新时间:2023-12-04 20:00:22 24 4
gpt4 key购买 nike

Dim myarray(2) as Variant

myarray(0)="3"
myarray(1)="4"
myarray(2)="5"
myarray(3)="9"

我想让它变成
myarray(0)=3
myarray(1)=4
myarray(2)=5
myarray(3)=9

有什么方法可以让它没有循环,就在 1 行?
这适用于 Excel 2010。

我想要这样的东西,但它不起作用:
intArray = Array.ConvertAll(stringArray , Function(str) Int32.Parse(str))

最佳答案

遍历数组并逐一转换值已经足够快了。下面的代码片段显示了转换循环相对于执行单元 I/O 的速度:

Private Const I_MAX = 10000
Private Const J_MAX = 200
Private Declare Function GetTickCount Lib "kernel32.dll" () As Long

Sub ticktest()
Dim ticks As Long, i As Long, j As Long
Dim v() As Variant
Dim a() As Long 'VBA integers are internally stored as longs
Dim r As Range

Set r = [A1].Resize(I_MAX, J_MAX)
ReDim a(1 To I_MAX, 1 To J_MAX)

ticks = GetTickCount
v = r
Debug.Print "Read from range: " & GetTickCount - ticks

Debug.Print "Type of values in v(): " & TypeName(v(1, 1))

ticks = GetTickCount
For i = 1 To I_MAX
For j = 1 To J_MAX
a(i, j) = v(i, j)
Next j
Next i
Debug.Print "Copy with cast to Long: " & GetTickCount - ticks

ticks = GetTickCount
For i = 1 To I_MAX
For j = 1 To J_MAX
v(i, j) = CLng(v(i, j))
Next j
Next i
Debug.Print "In-place cast to Variant/Long: " & GetTickCount - ticks

ticks = GetTickCount
r = a
Debug.Print "Write from long array: " & GetTickCount - ticks

ticks = GetTickCount
r = v
Debug.Print "Write from variant array: " & GetTickCount - ticks

For i = 1 To I_MAX
For j = 1 To J_MAX
v(i, j) = CStr(v(i, j))
Next j
Next i
r = v
End Sub

使用 I_MAX 的这些值和 J_MAX我们得到一个包含 2,000,000 个条目的数组,其中读取和写入工作表比从 Variant/String 转换每个条目慢大约 4 倍。到 Long :
Read from range: 749
Type of values in v(): String
Copy with cast to Long: 546
In-place cast to Variant/Long: 842
Write from long array: 921
Write from variant array: 1248

Read from range: 749
Type of values in v(): String
Copy with cast to Long: 546
In-place cast to Variant/Long: 827
Write from long array: 905
Write from variant array: 1248

Read from range: 749
Type of values in v(): String
Copy with cast to Long: 531
In-place cast to Variant/Long: 826
Write from long array: 905
Write from variant array: 1279

所以没有真正需要避免循环,有一个警告:如果你在循环中执行单元 I/O,性能会变得很糟糕。例如,这里是 r(i, j) = v(i, j) 的循环。需要整整 100 秒(即 100,000 个滴答声,或转换循环时间的 2,000 倍)才能完成。

关于arrays - vba Excel 2010 : convert string array into int array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18091413/

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