我有一个列表,我想删除某些文本
在上面提到的列表中,我想删除前后的HY以及_
之前和之后的符号-
以及符号_
之后的所有内容,如LEE SPRING所述第4项,不得删除-2E或-12作为最后一项。有人可以帮忙解决这个问题。上面提到的列表将是每个单元格的单个项目。
这是我的代码......但问题是我无法在""之后删除文字。如第4项清单所示
Sub Replace_Characters()
row_number = 1
Do
DoEvents
row_number = row_number + 1
the_description = Sheet2.Range("A" & row_number)
the_description = Replace(the_description, "HY", "")
the_description = Replace(the_description, "HY-", "")
the_description = Replace(the_description, "_HY", "")
the_description = Replace(the_description, "-HY", "")
the_description = Replace(the_description, "HY", "")
Sheet2.Range("A" & row_number) = the_description
Loop Until row_number = 20
End Sub
答案 0 :(得分:0)
left(the_description,instr(the_description,"_")-1)
会在您的文字中删除“_”及其后的所有内容
如果您做了很多替换,那么在VBA中使用正则表达式将是您的最终解决方案。互联网上有很多支持材料。
答案 1 :(得分:0)
我建议写一个函数。向函数发送您想要的信息,所有规则都可以像这样:
Function CleanData(Description As String) As String
Description = Replace(Description, "HY_", "", 1)
Description = Replace(Description, "_HY", "")
Description = Replace(Description, "HW-", "", 1)
Description = Replace(Description, "-HY", "")
Dim DescriptionArray() As String
DescriptionArray = Split(Description, "_")
Description = DescriptionArray(0)
CleanData = Description
End Function
Sub Test()
MsgBox CleanData("HY_5AP001KL10"), vbOKOnly + vbInformation, "Expected: 5AP001KL10"
MsgBox CleanData("5AP0015K20_HY"), vbOKOnly + vbInformation, "Expected: 5AP0015K20"
MsgBox CleanData("HW-5AP002H20"), vbOKOnly + vbInformation, "Expected: 5AP002H20"
MsgBox CleanData("5AP002lE_LEE SPRING"), vbOKOnly + vbInformation, "Expected: 5AP002lE"
MsgBox CleanData("NAS4021-2E-12"), vbOKOnly + vbInformation, "Expected: NAS4021-2E-12"
End Sub
我已经测试了5个用例,输出对我来说很好,但请随意修改它以满足您的需求。