[英]VBA / excel macro - find part of string in list of values and then return that value
[英]How to VBA Excel Macro part of a string
我目前正在忙于Excel工具和学习很多东西,但是我有一个问题。 目前我有几行数据。 在行中有很多数据,但我需要该行的特定部分。 当然,我可以手动将其全部删除,但是这样做3000行会浪费很多时间。
谁能帮我一个过滤数据的宏。 我需要的数据在[和]之间,因此例如[数据]
希望你们能帮助我,如果您需要更多信息,请问我! 我希望你们能帮助我!
示例字符串ROW:
[Sandwitch]><xsd:element name="T8436283"
那我需要什么?
因此,我需要一个仅将Sandwitch移出该宏并将其粘贴到B列中的宏。 包含所有信息的字符串位于A列,Sandwitch进入B列,所有行都保留。
选项1:查找/替换1)将数据复制到另一列中(仅保存原始副本)2)执行查找/替换“ * [” 3)执行查找/替换“]”现在您有了[]之间的数据。
选项2:使用公式1)假定“ A”列中的原始数据2)在“ B”列中应用此公式,该公式将提取[] = MID(A1,FIND(“ [”,A1)+1, FIND(“]”,A1)-FIND(“ [”,A1)-1)
选项3:宏如果绝对需要,我可以帮助创建一个宏,否则请尝试前两个简单的选项。
如果您想用正则表达式弄湿,下面的代码将带您到那里。 您必须添加对VB脚本库的引用
Tools > References > Microsoft VBScript Regular Expressions 5.5
然后代码如下:
Sub textBetweenStuffs()
Dim str As String
Dim regEx As RegExp
Dim m As Match
Dim sHolder As MatchCollection
Dim bracketCollection As Collection
Dim quoteCollection As Collection
Set regEx = New RegExp
'Matches anything in between an opening bracket and first closing bracket
regEx.Pattern = "\[(.*?\])"
str = "[Sandwitch]><xsd:element name=""T8436283"""
'populates matches into match collection
Set sHolder = regEx.Execute(str)
Set bracketCollection = New Collection
'loop through values in match collection to do with as you wish
For Each m In sHolder
bracketCollection.Add m.Value
Next i
Set sHolder = Nothing
'get values between Quotations
regEx.Pattern = "\"(.*?\")"
'populates matches into match collection
Set sHolder = regEx.Execute(str)
Set quoteCollection = New Collection
'loop through values in match collection to do with as you wish
For Each m In sHolder
quoteCollection.Add m.Value
Next i
End Sub
通用的“在s中找到元素,从x开始到下一个y ”:
Function GenExtract(FromStr As String, _
StartSep As String, EndSep As String) _
As Variant
Dim StPos As Long
Dim EnPos As Long
GenExtract = CVErr(xlErrNA)
If StartSep = "" Or EndSep = "" Then Exit Function 'fail
StPos = InStr(1, FromStr, Left(StartSep, 1))
If StPos = 0 Or StPos = Len(FromStr) Then Exit Function 'fail
EnPos = InStr(StPos + 1, FromStr, Left(EndSep, 1))
If EnPos = 0 Then Exit Function 'fail
GenExtract = Mid(FromStr, StPos + 1, EnPos - StPos - 1)
End Function
如果两个分隔符都相同,则用引号将其引起的第一个字符串括起来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.