如何在excel中使用VBA删除'*'或'-'字符后的文本?

use*_*966 5 excel

我编写了以下代码来删除一行中使用 VBA 中的一行中的“*”或“-”字符之后的文本,但它给出了错误。任何人都可以帮忙吗?

Sub Removetext()

For each c In Range("A1:ZZ1")
    c.Value = Left(c.Value, InStr(c.Value, "-") - 1)
Next C

End Sub
Run Code Online (Sandbox Code Playgroud)

Sco*_*ner 5

正如@JNevill 和@fidnwindow 的评论中所说,您需要测试是否找到了您搜索的对象:

Sub Removetext()

For Each c In Range("A1:ZZ1")
    If InStr(c.Value, "-") > 0 Then
        c.Value = Left(c.Value, InStr(c.Value, "-") - 1)
    End If
        If InStr(c.Value, "*") > 0 Then
        c.Value = Left(c.Value, InStr(c.Value, "*") - 1)
    End If
Next c

End Sub
Run Code Online (Sandbox Code Playgroud)

问题是当 InStr 没有找到它返回的条件时0。所以现在您正在寻找将抛出和错误的 Left -1 字符。

  • 只是作为一个提示:不需要`> 0`...但是,大多数人不喜欢那样:P (2认同)
  • @BruceWayne 它只有在没人能再读的时候才看起来很聪明......尝试像这样处理`[ranges]`和`:`:`Sub Removetext(): Dim c: For Each c In [A1: ZZ1]: If InStr(c.Value, "-") + InStr(c.Value, "*") Then c.Value = Left(c.Value, InStr(Replace(c.Value, "-", "* "), "*") - 1): Next: End Sub`(它只需要一行):D (2认同)