Excel无限循环问题

时间:2015-12-11 16:12:21

标签: excel excel-vba infinite-loop vba

此程序的目的是从单元格中删除字母。出于某种原因,当替换功能线执行时,它会陷入无限循环。如果单元格包含456po83,一旦变量递增,直到它们都等于p,单元格中的字母应该替换为空,o现在是字符串中的第4个字符,变量应该保持递增吗?我在这里缺少什么?

Option Explicit

Sub DeleteB()

Dim stringLength As Integer
Static str As String
Dim A As Integer
Dim num As Integer
Dim indvChar As String
Dim B As Integer
Dim charArray(0 To 25) As String

charArray(0) = "a"
charArray(1) = "b"
charArray(2) = "c"
charArray(3) = "d"
charArray(4) = "e"
charArray(5) = "f"
charArray(6) = "g"
charArray(7) = "h"
charArray(8) = "i"
charArray(9) = "j"
charArray(10) = "k"
charArray(11) = "l"
charArray(12) = "m"
charArray(13) = "n"
charArray(14) = "o"
charArray(15) = "p"
charArray(16) = "q"
charArray(17) = "r"
charArray(18) = "s"
charArray(19) = "t"
charArray(20) = "u"
charArray(21) = "v"
charArray(22) = "w"
charArray(23) = "x"
charArray(24) = "y"
charArray(25) = "z"

Do Until IsEmpty(Selection)

    A = 1
    num = Len(Selection)
    str = Selection.Value
     Do Until A = num + 1
     indvChar = Mid(str, A, 1)

        B = 0
        Do Until B = 26

            If indvChar = charArray(B) Then
            Selection.Value = Replace(str, indvChar, "", 1)

            Else: B = B + 1
            End If


        Loop

    A = A + 1
    Loop

ActiveCell.Offset(1, 0).Select
Loop

End Sub

2 个答案:

答案 0 :(得分:2)

如果你想找到这些数字,你会更容易找到你想要的东西而不是你想要的东西。

Sub DeleteB()

Dim rng As Range
Dim str As String
Dim i As Integer

Set rng = Selection

Do
    For i = 1 To Len(rng.Value)
        'If your local settings uses ',' as the deliniation to decimal then change the '.' to ','
        If IsNumeric(Mid(rng.Value, i, 1)) Or Mid(rng.Value, i, 1) = "." Then
            str = str & Mid(rng.Value, i, 1)
        End If
    Next i
    rng.Value = CDbl(str)
    Set rng = rng.Offset(1)
Loop Until rng = ""

End Sub

如果您只想替换数组中的值,则只需要一个循环。

Sub DeleteB()


Dim B As Integer
Dim charArray
Dim rng As Range

Set rng = Range(Selection, Selection.End(xlDown))

charArray = Array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z")


For B = LBound(charArray) To UBound(charArray)
        rng.Replace What:=charArray(B), replacement:="", Lookat:=xlPart, MatchCase:=False
Next B


End Sub

这会立即查看整个范围。用于填充数组的方法将允许您添加其他任何需要删除的项目,而不是添加到array()行。我的猜测是你想要添加空格和其他非数字项目。

答案 1 :(得分:2)

这个循环是问题所在:

    Do Until B = 26

        If indvChar = charArray(B) Then
        Selection.Value = Replace(str, indvChar, "", 1)

        Else: B = B + 1
        End If


    Loop

如果找到该字符,则将其替换为空,但不会增加循环计数器。将B = B + 1放在If块之外。