使用Mid和Excel在Excel中查找(VBA)提取子string并更改单元格值
我想遍历一个列并提取每个单元格内的子string(在我的例子中,“代码:”)
我想遍历每个单元格并运行公式。 基本上删除列的每个单元格中的所有内容,除了代码。
我知道如何使用公式将string提取到另一列B:= MID(A2,FIND(“Code:”,A2,1),23)
…但我想在同一个cell.I尝试在vba这个代码,但不知道我在做什么错:
For Each cell In Range("A:A") cell.Value = Mid(.Value, InStr(1, .Value, "Code:"), 23) Next
你的代码中有两个主要的错误:
- 使用没有
With
块的.Value
来定义哪个对象是Value
(如PeterT在注释中指出的那样),以及 - 试图处理列A中的每个单元格,其中很多(大多数?)根本不包含任何值,绝对不是您要查找的string。
重构代码:
Dim CodeExists As Long 'Only run the loop across cells that contain data: For Each cell In Range("A1", Cells(Rows.Count, "A").End(xlUp)) With cell CodeExists = InStr(1, .Value, "Code:") 'Check that "Code:" exists If CodeExists > 0 .Value = Mid(.Value, CodeExists, 23) End If End With Next
而且,正如加里的学生问,你为什么使用23? “Code:xxxx-xxxx-xxxx”的长度是20个字符,而不是23个,所以你会抓取比我想象的更多的3个字符。
PS如果您甚至不希望“代码:”留在最终结果中,您可以将您的Mid
语句更改为:
.Value = Mid(.Value, CodeExists + 6, 14)