通过数组高效循环

时间:2016-10-17 23:42:34

标签: arrays excel vba excel-vba loops

我有一列全名,我想用首字母替换。

我目前正在这样做:

Dim n As Long
Dim varray As Variant
Dim FullNameRange As Range
Dim FullName As String

varray = Range(NDLstaffCol & FirstLineItemRow & ":" & staffCol & LastRow + 1)

For n = FirstLineItemRow To UBound(varray, 1)
    Set FullNameRange = ActiveSheet.Range(staffCol & n)
    FullName = FullNameRange.Value
    FullNameRange = Left(FullName, 1) & Mid$(FullName, InStr(FullName, " ") + 1, 1)
Next

其中LastRow将最后一条记录称为全局变量。

与同一模块中的其他子程序相比,这需要很长的时间来处理。

有更好的方法吗?

作为参考,我从不知道全名,因此硬编码的查找/替换不起作用。有<500条记录。

1 个答案:

答案 0 :(得分:3)

Dim n As Long, rng As Range
Dim varray As Variant
Dim FullNameRange As Range
Dim FullName As String, v

Set rng = Range(staffCol & FirstLineItemRow & ":" & staffCol & LastRow + 1)
varray = rng.Value

For n = 1 To UBound(varray, 1)
    v = varray(n, 1)
    varray(n, 1) = Left(v, 1) & Mid$(v, InStr(v, " ") + 1, 1)
Next

rng.Value = varray