从单元格删除逗号和任何VBA后

我有下面的代码,我用来删除空格后的任何东西。

For i = 2 To lastRow33 If InStr(ws3.Cells(i, 28), " ") > 0 Then y = Replace(ws3.Cells(i, 28), " *", "") x = Left(y, InStr(y, " ") - 1) ws3.Cells(i, 28) = x End If Next I 

我试图修改它以从string的末尾删除一个逗号,以及任何后面的逗号。 我只是不断溢出,即使我没有声明任何整数只是龙。

 For i = 2 To lastRow33 If InStr(ws3.Cells(i, 28), " ") > 0 Then y = Replace(ws3.Cells(i, 28), ",*", "") x = Left(y, InStr(y, " ") - 1) ws3.Cells(i, 28) = x End If Next I 

任何想法我可能做错了什么? 下面的声明

 Dim lastRow33 As Long Dim ws3 As Worksheet Dim i As Long, j As Long 

您正在检查单元格中是否存在空格,而不是逗号。 相应地更改了您的代码。

 For i = 2 To lastRow33 If InStr(ws3.Cells(i, 28), ",") > 0 Then `changed space to comma here y = Replace(ws3.Cells(i, 28), ",*", "") x = Left(y, InStr(y, ",") - 1) `changed space to comma here ws3.Cells(i, 28) = x End If Next I 

编辑:

溢出错误可能源自InStr函数,因为它将始终返回一个整数。 这当然取决于单元格文本的长度。

不过,你基本上做了两次相同的操作。 在Y之下,用“”replace后面的逗号。

然后在X下,你会看Y的逗号结果,这是因为你在Y中的操作而不再存在,并且把字符带到左边。 较短的代码做同样的将是:

 For i = 2 to lastRow33 If InStr(ws3.Cells(i, 28), ",") > 0 Then ws3.Cells(i, 28) = Replace(ws3.Cells(i, 28), ",*", "") End if Next i 

如果这仍然导致溢出,那很可能是由于InStr结果很大而被存储在一个整数中。 您可以使用以下方法强制其值:

 For i = 2 to lastRow33 If CLng(InStr(ws3.Cells(i, 28), ",")) > 0 Then ws3.Cells(i, 28) = Replace(ws3.Cells(i, 28), ",*", "") End if Next i