[英]Excel VBA Extract Text from a Cell
我曾尝试通过Stack Overflow寻找以前的建议,但没有找到任何可行的方法。
这是我的情况:我正在尝试查看一个简单的Excel工作表,该工作表显示某人的姓名,职位以及他们的“角色”,这是我正在创建的自定义字段。 现在,我希望只做“工程师”,但还将扩展到“管理助手”和“经理”之类的东西。 (真正的电子表格长约8100行)。
我所需要做的就是浏览“标题”列,查看它是否与字符串匹配(在这种情况下,我的测试字符串是工程师),然后复制字符串以及其余的I或II或III,或者在某些情况下,四之后。
我听说过使用正则表达式,并且之前在SQL中使用过正则表达式,但是却很难满足我的需要。 这是我尝试使用MID函数的当前代码:
Sub GetRole()
' Custom function written to take role out of official title
strRole = "Engineer" ' String to check for
Dim lrow As Integer ' Number of Rows
Dim Role As String ' Role to write into adjacent cell
lrow = Cells(Rows.Count, "B").End(xlUp).Row
For i = lrow To 2 Step -1
If InStr(1, Cells(i, 2), "Engineer") > 0 Then
Role = Mid(Cells(i,3)), 1, 5)
Cells.(i, 3).Value = Role
End If
Next i
End Sub
但这并不太奏效。 任何帮助或建议,将不胜感激。 我愿意提供任何必要的额外信息。
您可以使用正则表达式解决此问题。 首先,您需要转到工具>引用...来启用引用,然后启用Microsoft VBScript Regular Expressions 5.5
然后使用以下代码生成您的答案
Sub GetRole()
' Custom function written to take role out of official title
' Uncomment the below if using Early Binding i.e. you enable the reference
' Dim ReGex As New RegExp
' Comment below line if decide to use Late Binding (i.e. you enable the reference)
Dim ReGex As Object
Dim i As Long, lrow As Long ' Number of Rows
' Comment the below line if decide to use Late Binding (i.e. you enable the reference)
Set ReGex = CreateObject("VBScript.RegExp")
With ReGex
.Global = True
.IgnoreCase = True
.Pattern = "(Engineer\sI*\b)"
End With
With ActiveSheet
lrow = .Cells(.Rows.Count, "B").End(xlUp).Row
For i = lrow To 2 Step -1
If ReGex.test(.Cells(i, 2).Value2) Then .Cells(i, 3).Value2 = Trim(ReGex.Execute(Cells(i, 2).Value2)(0))
Next i
End With
End Sub
产生输出:
我认为与调试VBA和Regex相比,Excel公式将更易于扩展:
=IF(ISNUMBER( FIND("Engineer III", E4)), "Engineer III",
IF(ISNUMBER( FIND("Engineer II" , E4)), "Engineer II",
IF(ISNUMBER(SEARCH("Engineer *I" , E4)), "Engineer I", "")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.