excel - 如何将多个字符串提取到一个逗号分隔的字符串中?
问题描述
我找到了这个 VBA 代码。
目前提取的字符串被复制到它们自己的列中。
我想更新复制提取字符串的部分,以将所有提取的字符串放在同一列中(用逗号分隔)。
Option Explicit
Public Sub ExtractInfoFromSquareBrackets()
Dim wksRaw As Worksheet
Dim strPattern As String, strRaw As String, strMatch As String
Dim rngAllRows As Range, rngCell As Range
Dim lngLastRow As Long, lngIdx As Long
Dim objMatches As Object
Dim rgx As RegExp
Set rgx = New RegExp
'Set references up-front
Set wksRaw = ThisWorkbook.Sheets("raw")
strPattern = "(\[\S*?\])"
With rgx
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = strPattern
End With
'Find the last-occupied row on the raw sheet
lngLastRow = wksRaw.Cells.Find(What:="*", LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
'Get all the rows into a single range for easy looping
With wksRaw
Set rngAllRows = .Range(.Cells(1, 1), .Cells(lngLastRow, 1))
End With
'Loop through all the rows
For Each rngCell In rngAllRows
'Store the value from the cell for easy comparison
strRaw = CStr(rngCell.Value)
'If the string inside the cell hits our RegExp, start the operation
If rgx.Test(strRaw) Then
'Assign the matches inside the string to an object
Set objMatches = rgx.Execute(strRaw)
'Loop through the matches, removing the square brackets and
'writing the results to the neighboring cells
For lngIdx = 0 To (objMatches.Count - 1)
strMatch = objMatches.Item(lngIdx)
strMatch = Replace(strMatch, "[", "")
strMatch = Replace(strMatch, "]", "")
rngCell.Offset(0, lngIdx + 1).Value = strMatch
Next lngIdx
Else
rngCell.Offset(0, 1) = "No square brackets found!"
End If
Next rngCell
MsgBox "Completed!"
End Sub
解决方案
您可以将循环修改为:
strMatch = vbnullstring
For lngIdx = 0 To (objMatches.Count - 1)
strMatch = strMatch & "," & objMatches.Item(lngIdx)
Next lngIdx
strMatch = Replace(strMatch, "[", "")
strMatch = Replace(strMatch, "]", "")
rngCell.Offset(0, 1).Value = Mid$(strMatch, 2)
推荐阅读
- .htaccess - .htaccess 难以根据最后一页反斜杠“/”确定要使用的文件
- php - 带着laravel护照大摇大摆不工作
- search - 如果我在具有逗号分隔数字的文本字段上使用通配符搜索,Alfresco SOLR4 不会给出结果
- javascript - 使用 Javascript 生成和读取受密码保护的 ZIP
- deep-learning - 如何使用 ModelCheckpoint 回调加载我的张量流模型?
- google-apps-script - 如何使用谷歌应用脚本每隔一列洗牌?
- angular - 未在子延迟加载的路由上调用父解析器
- javascript - 如何在react中提交表单时进行多个api调用
- c - C中函数调用的返回循环问题
- mysql - 在mysql中具有多列的单行输出,我可以在多行中填充这些列吗