简体   繁体   English

在最后一个空格处拆分单元格 excel VBA

[英]Split cell at last space excel VBA

I am trying to split a value inside a cell at the last space.我试图在最后一个空格处拆分单元格内的值。 For example, I want Abbey Road 4 split to Abbey Road and 4例如,我希望Abbey Road 4拆分为Abbey Road4

I need this to be done with VBA, not a Formula, as I need to delete the original Column afterwards.我需要用 VBA 来完成这个,而不是一个公式,因为我需要在之后删除原始列。

Look at INSTRREV to find the last occurrence of a string within a string.查看 INSTRREV 以查找字符串中最后一次出现的字符串。 https://msdn.microsoft.com/en-us/library/hsxyczeb(v=vs.84).aspx https://msdn.microsoft.com/en-us/library/hsxyczeb(v=vs.84).aspx

Sub Test()

    SplitText ThisWorkbook.Worksheets("Sheet1").Range("A1:A11")

End Sub

Sub SplitText(SrcRange As Range)

    Dim rCell As Range

    For Each rCell In SrcRange.Cells
        rCell.Offset(, 1) = Left(rCell, InStrRev(rCell, " ") - 1)
        rCell.Offset(, 2) = Mid(rCell, InStrRev(rCell, " ") + 1)
    Next rCell

End Sub

Here is a variation on the answer from Darren Bartrup-Cook ...这是 Darren Bartrup-Cook 答案的一个变体......

Assume cell A2 has the text Some text with spaces in it, below will put Some text with in C2 and spaces in D2假设单元格A2已文本Some text with spaces在里面,下面就会把Some text with在C2和spaces在D2

'Get text from A2
theText = Cells(2, 1).Value

'Get text to the left of last space
newTextLeft = Left(theText, InStrRev(theText, " ") - 1)
Cells(2, 3).Value = newTextLeft

'Get text to right of last space
newTextRight = Mid(theText, InStrRev(theText, " ") + 1)
Cells(2, 4).Value = newTextRight

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM