excel - 如何在下一列中的分隔符“:”,“,”之间拆分文本?
问题描述
我很难弄清楚如何在 VBA 中解决这个问题。我需要在其各自的单元格中输入正确的信息,例如:
在单元格范围内,名称应该只是第一行的名称 Amanda...
我一直在使用宏,但它不起作用,因为它只适用于 1 个分隔符。知道如何解决这个问题吗?
解决方案
试试这个代码
Sub SplitValuesToNextColumns()
Dim rng As Range, cl As Range, str As String
Dim regex As Object, mc As Object
Set regex = CreateObject("VBScript.regexp")
regex.ignorecase = False
regex.Global = True
On Error Resume Next
Set rng = Application.InputBox(Prompt:="Select column range" & vbLf & _
"Macro result will spill in the next 4 columns of the selected range", _
Title:="Select Range", Default:="B3", Type:=8)
On Error GoTo 0
If rng Is Nothing Then Exit Sub
For Each cl In rng
str = Replace(Replace(Replace(Replace(cl.Value, _
"1-Name=", "["), _
", 2-Last Name=", "]["), _
", 3-Address=", "]["), _
", 4-Status=", "][") & "]"
regex.Pattern = "\[[^]]+\]"
Set mc = regex.Execute(str)
For i = 0 To mc.Count - 1
Cells(cl.Row, cl.Offset(, i + 1).Column) = _
Mid(mc(i), 2, Len(mc(i)) - 2)
Next i
Next cl
End Sub
编辑 - 不需要正则表达式
正如@RaymondWu 在下面的评论中所建议的那样。
Sub SplitValuesToNextColumns()
Dim rng As Range, cl As Range, str As String, arr
On Error Resume Next
Set rng = Application.InputBox(Prompt:="Select column range" & vbLf & _
"Macro result will spill in the next 4 columns of the selected range", _
Title:="Select Range", Default:="B3", Type:=8)
On Error GoTo 0
If rng Is Nothing Then Exit Sub
For Each cl In rng
str = Replace(Replace(Replace(Replace(cl.Value, _
"1-Name=", ""), _
", 2-Last Name=", "|"), _
", 3-Address=", "|"), _
", 4-Status=", "|")
arr = Split(str, "|")
cl.Offset(, 1).Resize(1, UBound(arr) + 1) = arr
Next cl
End Sub
推荐阅读
- typescript - 处理回调
定义 - android - 如何快速更改 Imageresource?
- c++ - 断言失败 CV_Assert( CV_IS_MAT(objectPoints) && CV_IS_MAT(imagePoints) && CV_IS_MAT(A) && CV_IS_MAT(rvec) && CV_IS_MAT(tvec) )
- r - 如何使用 R 中的条件计算日期之间的差异
- jquery - 使用wicket 7.10.0,如何更改jquery 3.2.1的打包版本
- javascript - 这两个函数定义有什么区别
- python-3.x - 当 range() 足够时,为什么 Matplotlib 文档使用 numpy.arange() ?
- java - 已经使用 id "org.springframework.boot" 插件时我们是否需要 "io.spring.dependency-management" gradle 插件
- python - 如何使用线性判别分析根据序列值进行预测
- python-3.x - Python 3.7.3 导入子进程抛出错误