如何用VBA中的Do循环replace列中的string中的值

我有一列电话号码。 其中一些包含两个连续的连字符“ – ”,而不是一个“ – ”。 我想用“ – ”replace“ – ”。
问题是如果“ – ”每个单元格只出现一次,那很好,但是可能有“—-”或“—”,甚至“——– —”。 我的直觉是使用Do While或Until Loop,但我不知道如何。 我想我会需要查找function,但我不知道如何将它们结合起来。
请有人帮助我好吗?
谢谢。

尝试这个

Sub rep() For Each c In Sheets("Sheet1").Range("A1:A10").Cells ' Change the range that you want If InStr(c.Value, "--") > 0 Then deli = Split(c, "-") For a = 0 To UBound(deli) c.Value = Replace(c.Value, "--", "-") Next a End If Next c End Sub 

令人难以置信的复杂和无效的答案我看!

 Range("c3:c17").Replace "--", "-" Range("c3:c17").Replace "--", "-" 

应该用2行代替最多4个连字符,也许比复杂的答案快得多。 添加第三行以处理最多6个连续的连字符。

如果连续连字符的数量可能非常大(不像在OP中),那么下面的循环可能会更好:

 With Range("c3:c17") Do Until .Find("--") Is Nothing .Replace "--", "-" Loop End With 

不要忘记,从VBA访问电子表格是一个昂贵的操作。 使用1代替一个范围比单元格更快。 当然,这只有在处理大量数据时才可见。

 Sub CorrectTelephoneNo() Dim strHypens strHypens = "--" Dim strFound As Boolean strFound = True 'Assuming there is atleat on cell with "--" Do While (strFound = True) 'Replace all the "--" with "-" Cells.Replace What:="--", Replacement:="-", LookAt:=xlPart, SearchOrder _ :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False 'Check if there are any more numbers with "--" On Error GoTo x strFound = Cells.Find(What:="--", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _ xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _ , SearchFormat:=False).Activate GoTo y x: strFound = False y: Loop MsgBox "done" End Sub 

你可以尝试一个recursion函数来做到这一点,例如:

 function recursiveReplace(text as string, oldText as string, newText as string) as string dim result as string result = replace(text, oldText, newText) if instr(1, result, oldText) > 0 then recursiveReplace = recursiveReplace(result, oldText, newText) else recursiveReplace = result end if end function sub test() const phoneNumber as string = "234-45---34----112" debug.print recursiveReplace(phoneNumber, "--", "-") end sub 

你现在可以直接在Excel工作表中调用这个函数了! 例如= recursiveReplace(“234 — 456 —– 67–5”,“ – ”,“ – ”)

将一个公式足以取代 – 与 – ? 就像是:

 =SUBSTITUTE(A1,"--","-") 

在VBA中,有各种各样的方法,但是这里会给你一个循环等的想法…

 Option Explicit Sub ReplaceDashes() Dim r As Range, r1 As Range Set r = Sheet1.Range("A1:A10") For Each r1 In r If InStr(1, r1.Value, "--") >= 0 Then r1.Value = Application.WorksheetFunction.Substitute(r1, "--", "-") Next End Sub 

希望有帮助..

尝试这个 :

 Dim my_switch As Boolean my_switch = True Do While my_switch = True If InStr(Worksheets("Sheet1").Range("A1").Value, "--") > 0 Then Worksheets("Sheet1").Range("A1").Value = Replace(Worksheets("Sheet1").Range("A1").Value, "--", "-") Else my_switch = False End If Loop