如何从单元格中提取特定的文本?
在这种情况下,我想提取一个单元格中的开始文本,并保持其余的完整。 例如一系列单元包含:
2nd Unit. Miami 3rd Production Staff. Toronto 1st Ad. San Francisco
我想打破这一点,而不使用文本到列,因为以前的行格式不同,这些最后几行是我想处理的exception。
我认为正则expression式可能会这样做,但是这似乎有点复杂。
我的algorithm的想法是:1.抓住想要的文本(什么函数或自定义子将做到这一点?)2.通过文本到它的新位置3.从单元格中剪切文本,留下剩余的文本。
看起来很简单,但我依然在通过VBA森林,我正在以最快的速度做手工。 但这似乎是学习一些VBA技巧的好机会。
TIA
更新:我想把文本放到“。\”,并把它移到不同的列,保留其余的位置。
由于您似乎想要修改单元格文本,VBA将是必需的。
在将cl
设置为要处理的单元的循环中:
str = cl.value i = Instr(str, ".\") cl = Trim(Mid$(str, i + 2)) ' assuming you want to exclude the ".\" cl.Offset(0, 1) Trim(Left$(str, i - 1)) ' Places the original first part one cell to the right
VBA是不必要的。 要在A1: =MID(A1,FIND(".\",A1,1)+2,LEN(A1))
中的单元格A1中获取文本,在A1: =LEFT(A1,FIND(".\",A1,1)-1)
。
作为附加信息, Find
将返回出现在.\
的string中的位置。 这相当于VBA中的InStr
。 如果.\
不在单元格中,它将显示#VALUE
,因为我没有打扰添加错误检查。
为了任何人有这个相同的问题,这里是完全testing,工作代码。
Function RE6(strData As String) As String Dim RE As Object, REMatches As Object Set RE = CreateObject("vbscript.regexp") With RE .MultiLine = False .Global = False .IgnoreCase = True .Pattern = "[0-9][0-9][0-9][0-9]B" RE6 = .test(strData) End With Set REMatches = RE.Execute(strData) If REMatches.Count > 0 Then RE6 = True Else RE6 = False End If End Function Sub territory() Dim strTest As String, str As String, cl As Range strTest = ActiveCell.Value Set cl = ActiveCell If RE6(strTest) = True Then str = cl.Value i = InStr(str, ". ") cl = Trim(Mid$(str, i + 2)) cl.Offset(0, 1) = Trim(Left(str, i - 1)) cl.Offset(0, 2) = "Instance" MsgBox RE6(strTest) End If End Sub