如何在 excel 中提取某些以单词开头的字符串,该行包含多个逗号分隔的字符串?



>我在 excel 中有以下行:['牛奶', '蜂蜜牛奶', '面包', '牛奶加面包', '黄油', '牛奶加黄油'] 我希望能够在单独的列或同一列中提取以单词"milk"开头的所有字符串。 提取物应如下所示:牛奶,蜂蜜牛奶,面包牛奶,黄油牛奶。

这是 VBA 方法的粗略版本。显然,您必须将其放入适当的循环中才能应用于整个工作表。也许需要更多的错误处理,但它应该给你一个想法:

Sub extract_string()
Dim l As Long
Dim search_string As String
Dim next_item As Integer
Dim next_col As Integer
search_string = Cells(1, 1).Value
For l = 1 To Len(search_string) 'loop through string
If (Mid(search_string, l, 4) = "milk") Then 'check, if milk
On Error GoTo Last_Item
next_item = WorksheetFunction.Find(",", search_string, l + 1)
next_col = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column + 1 'find end
If (next_item <> 0) Then
Cells(1, next_col).Value = Mid(search_string, l, next_item - l)
Else
Last_Item:
Cells(1, next_col + 1).Value = Mid(search_string, l, Len(search_string) - l + 1) 'last item handling
End If
End If
next_item = 0
Next l
End Sub

为了简单起见,我假设您的初始字符串如下所示:

牛奶,蜂蜜牛奶,

面包,面包牛奶,黄油牛奶,黄油牛奶

。并且它存储在名为Sheet1的工作表的cell A1中。

为了让我的生活更轻松,我要做的第一件事就是使用Text to Columns并将comma定义为分隔符。这会根据需要将您的初始字符串拆分为任意数量的单元格,第一个单元格存储在A1中。

然后,要找到哪个单独的字符串以单词milk开头并将它们组合成一个名为output的新字符串,我将执行以下操作:

Option Explicit
Sub milk()
Dim output As String
Dim inputRng As Range, cell As Range
Dim sht As Worksheet
Set sht = ThisWorkbook.Worksheets("Sheet1")
output = ""
With sht
Set inputRng = .Range(.Range("A1"), .Cells(1, .Columns.Count).End(xlToLeft))
End With
For Each cell In inputRng.Cells
If InStr(1, cell.Value, "milk") = 1 Then
output = output & cell.Value & ", "
End If
Next cell
MsgBox output
End Sub

最新更新