gpt4 book ai didi

excel - 提高有关拆分字符串的 VBA 代码的性能

转载 作者:行者123 更新时间:2023-12-03 02:20:31 25 4
gpt4 key购买 nike

我需要执行以下操作:

我有一个表,其中第 13 列包含字符串,例如

acbd,ef,xyz
qwe,rtyu,tqyuiop

我想要创建新行以分隔这些值:

acbd
ef
xyz
qwe
rtyu
tqyuiop

这意味着我现在有 6 行而不是 2 行,并且单元格上的所有其他信息将保持不变(即该行的所有其他值将在所有新行中重复)。

我尝试过的方法如下:

Sub test()

Dim coma As Integer
Dim finalString As String

Set sh = ActiveSheet
For Each rw In sh.Rows

* If find a coma, then copy the row, insert a new row, and paste in this new row*

If InStr(1, sh.Cells(rw.Row, 13).Value, ",") Then

Rows(rw.Row).Copy
Rows(rw.Row).insert shift:=xlShiftDown
Rows(rw.Row).PasteSpecial xlPasteValues

* Now it will look for the position of the comma and assign
to finalString what's before the comma, and assign to mod String
what's after the comma *

coma = InStr(1, sh.Cells(rw.Row, 13).Value, ",")

finalString = Left(sh.Cells(rw.Row, 13).Value, coma - 1)
modString = Right(sh.Cells(rw.Row, 13).Value, Len(sh.Cells(rw.Row, 13).Value) - coma)

* Replace the values: *

sh.Cells(rw.Row, 13).Value = modString
sh.Cells(rw.Row - 1, 13).Value = finalString

End If

Next rw

MsgBox ("End")

End Sub

此代码运行良好,但对于 400 行的表需要 15 +-5 秒才能完成。

我想要一些关于如何提高性能的建议。谢谢!

最佳答案

使用L列中的数据,尝试一下:

Sub LongList()
Dim wf As WorksheetFunction, arr, s As String

Set wf = Application.WorksheetFunction

s = wf.TextJoin(",", True, Range("L:L"))
arr = Split(s, ",")
Range("M1").Resize(UBound(arr) + 1, 1).Value = wf.Transpose(arr)
End Sub

enter image description here

注意:

不循环单元格。
不循环单元格内。
此过程只需使用工作表公式即可完成,不需要 VBA。

关于excel - 提高有关拆分字符串的 VBA 代码的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53375873/

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