[英]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.