|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
跟论坛的文章是一类问题,可以在这下载练手文件https://www.excelhome.net/3422.html
平常比较习惯用EXCEL,但是又眼馋WPS的某些功能,心念一动 想着用用AIGC试试。试了下40w条数据,用2.2秒处理完了。但是赶紧WPS更胜一筹。
代码:
- Private regex As Object ' 静态的正则表达式对象
-
- Private Sub InitializeRegex() ' 初始化正则表达式对象
- If regex Is Nothing Then
- Set regex = CreateObject("VBScript.RegExp")
- regex.Global = True
- End If
- End Sub
-
- Function CleanStringWithRegex(ByVal inputString As String) As String
- InitializeRegex ' 确保 regex 已创建
- regex.Pattern = "\s+|^ | $" ' 合并两个替换操作的正则表达式
- CleanStringWithRegex = regex.Replace(inputString, "")
- End Function
-
- ' ... 其他代码保持不变,但在调用 CleanStringWithRegex 之前确保 InitializeRegex 已被调用 ...
- Sub CleanAndFormatAsText_RegexArray()
- Dim rng As Range
- Dim cellValues() As Variant
- Dim outputValues() As Variant
- Dim i As Long, j As Long, rowCount As Long, colCount As Long
- Dim startTime As Double
-
- startTime = Timer
-
- ' 确保用户已经选定了要处理的单元格范围
- If TypeName(Selection) <> "Range" Then
- MsgBox "请先选择一个单元格范围。", vbExclamation, "未选择范围"
- Exit Sub
- End If
-
- ' 将选定范围赋值给rng变量,并获取其尺寸
- Set rng = Selection
- rowCount = rng.Rows.Count
- colCount = rng.Columns.Count
-
- ' 读取数据到数组中
- cellValues = rng.Value2
- rng.NumberFormat = "@"
-
- ' 为输出值创建同样大小的数组
- ReDim outputValues(1 To rowCount, 1 To colCount)
-
- ' 关闭屏幕更新和计算,以提高性能
- Application.ScreenUpdating = False
- Application.Calculation = xlCalculationManual
-
- ' 在数组中处理数据
- For i = 1 To rowCount
- For j = 1 To colCount
- If Not IsEmpty(cellValues(i, j)) Then
- outputValues(i, j) = CleanStringWithRegex(CStr(cellValues(i, j)))
- Else
- outputValues(i, j) = ""
- End If
- Next j
- Next i
-
- ' 将处理后的数据写回Excel
- rng.Value2 = outputValues
-
- ' 设置单元格格式为文本
- 'rng.NumberFormat = "@"
-
- ' 恢复屏幕更新和计算
- Application.ScreenUpdating = True
- Application.Calculation = xlCalculationAutomatic
-
- ' 显示处理完成消息和所用时间
- MsgBox "选定范围内的异常字符已被清理,操作完成。" & vbCrLf & _
- "所用时间: " & FormatNumber(Timer - startTime, 2) & " 秒", vbInformation, "处理完成"
- End Sub
复制代码 与文心一言的对话过程
----------------------------------------------------------------------------------------------------------------------
|
评分
-
1
查看全部评分
-
|