【发布时间】:2021-10-05 20:07:32
【问题描述】:
我创建了这段代码,它应该用点替换选择中的逗号(如果有的话)。但是,如果选择以包含点的单元格开头,则该代码不起作用,但如果它以包含逗号的单元格开头,则该代码有效。如果它以逗号开头,然后是带有点的单元格,然后是带有逗号的单元格,它甚至可以工作。代码如下:
Public Sub DeleteDotsReplaceCommasWithDots()
For Each cell In Selection
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
If InStr(ActiveCell.Value, ".") > 0 And InStr(ActiveCell.Value, ",") > 0 Then
Selection.Replace What:=".", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
Selection.Replace What:=",", Replacement:=".", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
ElseIf InStr(ActiveCell.Value, ".") = 0 And InStr(ActiveCell.Value, ",") > 0 Then
Selection.Replace What:=",", Replacement:=".", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False, FormulaVersion:=xlReplaceFormul
End If
Next cell
End Sub
知道为什么会这样吗?谢谢:)
【问题讨论】:
-
欢迎来到 SO!我的印象是您循环遍历所有选定的单元格,但是,在每个循环中,您的条件都基于活动单元格,并且您在整个选择中进行替换。另外,我认为最后一个
Replace函数中的xlReplaceFormul是一个错字... -
嗨维克多,感谢您的回答。我修正了错字。我还用“ActiveCell.Replace”更改了“Selection.Replace”,但是当一个带有点的单元格是第一个单元格时,我仍然无法让代码工作。
-
ActiveCell不会解决问题,因为它不会随着For Each cell In Selection循环的每次迭代而改变。也许切换到cell。 -
所以我错误地理解了选择中的每个单元格,我的错!但是谢谢你,当我把它改成单元格时,它工作得很好! :)