在Excel中仅替换一系列单元格内的数字

时间:2019-07-10 11:01:28

标签: excel vba

我有一个excel列,它的单元格值是字符串,末尾带有一些数字。我无法执行``文本到列'',因为空格既不能是定界符也不可以是制表符。我尝试了以下代码,但仅在整个单元格只有一位数字时才有效     我是宏和vb的初学者

Sub ReplaceNoX()
 Dim cell As Object
 Dim val As String
 Dim i As Integer
 Dim n As String
 Application.ScreenUpdating = False
 For Each cell In Selection
 If IsNumeric(cell.Value) Then
 val = cell.Text
 For i = 1 To Len(val)
 n = Mid(val, i, 1)
 If "0" <= n And n <= "9" Then
 Mid(val, i, 1) = "x"
 End If
 Nextf
 cell.Formula = val
 End If
 Next
 Application.ScreenUpdating = True
 End Sub

2 个答案:

答案 0 :(得分:2)

如果您确实想用'x'替换每个数字,则这是使用正则表达式的另一种方法。

Sub Regex1()

Dim oRgx As Object, rCell As Range

Set oRgx = CreateObject("VBScript.RegExp")

With oRgx
    .Global = True
    .Pattern = "\d"
    For Each rCell In Selection
        rCell.Value = .Replace(rCell, "x")
    Next rCell
End With

End Sub

enter image description here

答案 1 :(得分:1)

如果您要同时更改数字以及混合的文本和数字,请删除 0 - 206 the 65 for 62 1 62 DAYS 56 测试:

IsNumeric()

注意:

  1. 使用Sub ReplaceNoX() Dim cell As Range Dim val As String Dim i As Long Dim n As String Application.ScreenUpdating = False For Each cell In Selection val = cell.Text For i = 1 To Len(val) n = Mid(val, i, 1) If n Like "[0-9]" Then Mid(val, i, 1) = "x" End If Next i cell.Value = val Next Application.ScreenUpdating = True End Sub 而不是Long
  2. 使用Integer检查单个字符。
  3. 使用Like而不是Range