Har*_*iec 2 arrays string int vba excel-vba
Dim myarray(2) as Variant
myarray(0)="3"
myarray(1)="4"
myarray(2)="5"
myarray(3)="9"
Run Code Online (Sandbox Code Playgroud)
我希望它成为
myarray(0)=3
myarray(1)=4
myarray(2)=5
myarray(3)=9
Run Code Online (Sandbox Code Playgroud)
有什么方法可以让它没有循环,只需一行?这适用于Excel 2010.
我想要这样的东西,但它不起作用:
intArray = Array.ConvertAll(stringArray , Function(str) Int32.Parse(str))
Run Code Online (Sandbox Code Playgroud)
循环遍历数组并逐个转换值足够快.下面是一段代码,显示转换循环相对于执行单元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
Run Code Online (Sandbox Code Playgroud)
使用这些值I_MAX,J_MAX我们得到一个2,000,000条目数组,其中读取和写入工作表比将每个条目从a转换Variant/String为a 慢大约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
Run Code Online (Sandbox Code Playgroud)
因此,没有必要避免循环,但有一点需要注意:如果在循环中执行单元I/O,则性能变得极差.例如,这里r(i, j) = v(i, j)需要一个完整的100秒(即100,000个刻度,或转换循环时间的2,000倍)的循环.
| 归档时间: |
|
| 查看次数: |
9784 次 |
| 最近记录: |