在Excel中提取string的一部分
我有这样一个string
“来自东京的汽车5在13:56:39到达33:53:03到达奥地利的汽车5在13:56:43到达33:53:07到达13:56:43的汽车来自印度的汽车5到达33:53:03 13:56:39时分“
在excel的同一个单元格中。
我需要at 13:56:39
at 13:56:43
13:56:39
显示在单独的单元格的string的这些部分。
请帮忙
我会有一个不同的方法,使用一个公式:
B列使用这个公式:
B1=IFERROR(SEARCH("at ??:??:??",A$1,1),"") B2=IFERROR(SEARCH("at ??:??:??",A$1,B1+11),"")
C列使用这个公式:
C1=IFERROR(PART(A$1,B1,11),"")
这些将为大量的事件工作。
如果你的数据是在一个单独的列中,我认为使用variables数组的正则Regexp
是有意义的。
但作为一个更灵活的选项你可以使用下面的UDF作为数组input公式来分割string
如果你的string在A1
中说,你最多预期5个匹配
- select
B1:F1
- 在公式栏中添加
=AtTime(A1)
- 按shift ctrl一起input
额外的不匹配将有#N / A
码
updated to handle single matches
Function AtTime(strIN As String) As Variant Dim objRegex As Object Dim objRMC As Object Dim strOut() As String Dim lngCnt As Long Set objRegex = CreateObject("vbscript.regexp") With objRegex .Global = True .Pattern = "at \d{2}:\d{2}:\d{2}" If .test(strIN) Then Set objRMC = .Execute(strIN) If objRMC.Count > 1 Then ReDim strOut(1 To objRMC.Count) For lnGCnt = 1 To UBound(strOut) strOut(lnGCnt) = objRMC(lnGCnt - 1) Next Else 'handle single matches ReDim strOut(1 To 2) strOut(1) = objRMC(0).Value strOut(2) = "#N/A" End If AtTime = strOut Else AtTime = "no match" End If End With End Function
向下和脏string操作:
Option Explicit Sub Test() Dim cellValue As String Dim newCellArray() As String Dim valueYouWant As String Dim cellCounter As Integer Dim x As Integer Dim myRange As Range Const SEPERATOR_VALUE = "at " Const ASCII_A = 65 For cellCounter = 1 To 10 '10 represents the last row...there are ways to set this dynamically if needed cellValue = Sheet1.Range("A" & cellCounter) newCellArray = Split(cellValue, "at ") 'Array is zero-based, but we want to start at first split value For x = 1 To UBound(newCellArray) valueYouWant = Trim$(Left$(newCellArray(x), InStr(1, newCellArray(x), " "))) 'You could prefix this with "at " if you really needed it Sheet1.Range(Chr$(ASCII_A + x) & cellCounter).Value = valueYouWant Next x Next cellCounter End Sub