Excel VBA – 如果最后一位是0,则用1replace

我有一个2位和3位数字的电子表格。 如果是以0结尾的3位数字,则最终的0应该被replace为1.因此,150变成151,200变成201。

这是我正在使用,只是为了testing的function,它是非常缓慢,通常崩溃Excel,因为(我认为)它本质上是做每个单元格上多次查找和replace,即使它已经取代了价值。 所以我觉得我需要走一条不同的路线。

Sub FixNumbers() Dim c As Range For Each c In Selection.Cells Selection.NumberFormat = "General" c = Replace(c, "100", "101") c = Replace(c, "150", "151") c = Replace(c, "200", "201") c = Replace(c, "250", "251") c = Replace(c, "300", "301") c = Replace(c, "350", "351") c = Replace(c, "400", "401") Next End Sub 

如果单元格包含2-3位数字 – 不要对其使用文本操作。 格式更改应该在循环之外。

 Sub FixNumbers() Dim c As Range Selection.NumberFormat = "General" For Each c In Selection.Cells If (c > 99) And (c Mod 10) = 0 Then c = c + 1 Next End Sub 

在vba中做到这一点:

 Sub FixNumbers() Dim c As Range Selection.NumberFormat = "General" For Each c In Selection.Cells If Len(c) = 3 And Right(c, 1) = "0" Then c.Value = CInt(Left(c, 2) & "1") End If Next End Sub 

我亲自做这个testing值模数10,然后加1:

 Sub FixNumbers() Dim height As Long Dim c As Range For Each c In Selection.Cells height = CLng(c.Value) If height > 99 And height < 1000 And height Mod 10 = 0 Then c.Value = height + 1 Next End Sub 

不要在VBA中这样做。 模仿一些工作表可以做的奇妙的是毫无意义的。

而是在工作簿中创build一个新列。 假设列A包含你的数字。

然后在新列中使用=IF(MOD(A1,10),A1,A1+1)向下复制。 (当且仅当数字以零结尾时, MOD(A1,10)为0)。