在Excel脚本中用点replace逗号

我想用点replace逗号,反之亦然

Public Sub VirgulaPunct() Dim oRow As Range Dim cell As Range Dim i As Long, j As Long Dim MyString As String Dim aux As String Application.ScreenUpdating = False For i = Selection(Selection.Count).Row To Selection.Cells(1, 1).Row Step -1 For j = Selection(Selection.Count).Column To Selection.Cells(1, 1).Column Step -1 MyString = Cells(i, j).Value For Counter = 1 To Len(MyString) aux = Mid(MyString, Counter, 1) If aux = "." Then MyString = Replace(MyString, ".", ",", 1) ElseIf aux = "," Then MyString = Replace(MyString, ",", ".", 1) End If Next Cells(i, j).Value = MyString Next j Next i Application.ScreenUpdating = True End Sub 

您可以使用Range对象的Replace方法

 Sub ReplacePunct() Const sTEMPCOMMA = "|comma|" Const sTEMPDOT = "|dot|" Const sCOMMA = "," Const sDOT = "." If TypeName(Selection) = "Range" Then With Selection .Replace sCOMMA, sTEMPCOMMA, xlPart .Replace sDOT, sTEMPDOT, xlPart .Replace sTEMPCOMMA, sDOT, xlPart .Replace sTEMPDOT, sCOMMA, xlPart End With End If End Sub 

基本的问题是,如果列设置为一般而不是文本,即使我们将“,”改为“。”。 Excell会自动将它更改为“,”。

为了避免这种情况,需要首先将列设置为文本格式,然后我们可以执行replacefunction:

这对我有用:

 Worksheets("Name").Activate Worksheets("Name").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select Selection.NumberFormat = "@" Dim OriginalText As String Dim CorrectedText As String LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row For i = 1 To LastRow OriginalText = Worksheets("Name").Cells(i, 1).Value CorrectedText = Replace(OriginalText, ",", ".") Worksheets("Name").Cells(i, 1).Value = CorrectedText Next i 

通过查看你的循环,你似乎不是多次访问任何单元格。 这不是一个简单的if语句在这里工作吗?

 if(Cells(i,j).Value = ',') Cells(i,j).Value = '.' Elsif(Cells(i,j).Value = '.') Cells(i,j).Value = ',') End 

从VB的angular度来看,而不是VBA,我会考虑使用内置的Replace函数,而不是循环遍历它。

所以首先我要全部取代, (或者如果可能的话;在文本中,我会使用其他的东西,可能是字符的组合,如;+;+或类似的),然后全部replace.,并最终取代所有;.
可能不是很有效率,但很容易。

这似乎是我对前一个问题的回答的延续,但如果是这样的话,我认为你误解了我的意思。 我已经把你的代码和修改了我的build议,但我没有testing它:

 Public Sub VirgulaPunct() Dim oRow As Range Dim cell As Range Dim i As Long, j As Long Dim MyString As String Dim aux As String Application.ScreenUpdating = False For i = Selection(Selection.Count).Row To Selection.Cells(1, 1).Row Step -1 For j = Selection(Selection.Count).Column To Selection.Cells(1, 1).Column Step -1 MyString = Cells(i, j).Value MyString = Replace(MyString, ",", ";+;", 1) MyString = Replace(MyString, ".", ",", 1) MyString = Replace(MyString, ";+;", ".", 1) Cells(i, j).Value = MyString Next j Next i Application.ScreenUpdating = True End Sub 

所以正如我在前面的回答中所说的那样,我会对“ Replace进行3次调用,但是我会为整个string而不是string中的每个字符执行这些调用。

为了将来的参考,如果你更新了原来的问题,而不是创build一个新的问题,然后你可以在我的回答下给我留下评论,我看到你已经这么做了。