![](/img/trans.png)
[英]EXCEL: Extracting Milliletres and Litres from cell using vba or formula
[英]Extracting Text from Cell using Excel VBA
我希望从 Excel 的列中提取多个文本值,并用这些文本值填充另一列。
更具体地说,我希望提取 STLS 票号。
例如,一行可能包含“ABCD-4, STLS-5644, ABBD-33, STLS-421”,另一行可能包含“ABB-567, STLS-56435”,另一行可能不包含 STLS 票证。
解决这个问题的最佳方法是什么?
你可以试试这段代码:
Option Explicit
Sub testExtract()
Dim i As Long, j As Long, jUp As Long, lFirstRow As Long, lLastRow As Long
Dim lColFrom As Long, lColTo As Long, nTicks As Long
Dim str1 As String
Dim varArray
'
' define source column number and the destination one:
'
lColFrom = 1
lColTo = 2
'
' initialize range to analyze:
'
lFirstRow = 1
lLastRow = Cells(Rows.Count, 1).End(xlUp).Row
'
' loop over the rows:
'
For i = lFirstRow To lLastRow
'
' split the string in the cell in an array:
'
varArray = Split(Cells(i, lColFrom).Value, ",")
jUp = UBound(varArray)
nTicks = 0
str1 = ""
'
' check the array element by element if we have some ticket:
'
For j = 0 To jUp
'
' trim spaces:
'
varArray(j) = Trim(varArray(j))
'
' check if we have ticks and count them:
'
If (InStr(1, varArray(j), "STLS-") > 0) Then
If (nTicks > 0) Then
str1 = str1 & ", "
End If
str1 = str1 & varArray(j)
nTicks = nTicks + 1
End If
Next
'
' save ticks:
'
If (str1 <> "") Then
Cells(i, lColTo).Value = str1
End If
Next
End Sub
If your Excel has the FILTERXML
function (windows Excel 2013+) and the TEXTJOIN
function, you don't need VBA.
您可以使用:
=IFERROR(TEXTJOIN(",",TRUE,FILTERXML("<t><s>" & SUBSTITUTE(A1,",","</s><s>")&"</s></t>","//s[contains(.,'STLS')]")),"")
如果你没有这些功能,你可以使用这个 VBA UDF:
Option Explicit
Function getTickets(s As String, ticket As String) As String
Dim v, w, x, col As Collection, i As Long
v = Split(s, ",")
Set col = New Collection
For Each w In v
If Trim(w) Like ticket & "*" Then col.Add Trim(w)
Next w
i = 0
If col.Count = 0 Then
getTickets = ""
Else
ReDim x(col.Count - 1)
For Each w In col
x(i) = w
i = i + 1
Next w
getTickets = Join(x, ",")
End If
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.