Excel VBA替换字符


2

我尝试查找此特定问题,但找不到它。

我正在尝试替换字符串中的各种字符。

我尝试使用字符代码循环遍历字符,但是我的代码会“随机”吗?删除整个字符串,而不只是特殊字符。(基本上我只想要字符串中的字母和数字)

ABC-3.3%H14T-6

我只想要

ABC33H14T6

对此(对我而言)奇怪的是,我的代码将删除随机字符上的字符串,这并不总是chr(41)或任何事情,每次运行代码时都会更改。.也许是格式问题?

 For Char = 33 To 47
    Sheets("Sheet1").Cells(FRow, 44).Replace What:=Chr(Char), Replacement:="", LookAt:=xlPart
 Next Char

我会给您大部分代码,但是它对工作敏感。

Answers:


0

替换您的操作方式将不起作用,因为这些非字母数字字符可能具有特殊功能,例如小丑等。您需要在VBA中而不是在Excel中进行替换。

因此,请尝试以下操作:

For Char = 33 To 47
    Sheets("Sheet1").Cells(FRow, 44).Value = Replace(Sheets("Sheet1").Cells(FRow, 44).Value, Chr(Char), "")
Next Char

1
我认为用正则表达式替换会更快,而不是遍历char代码。
tumchaaditya 2014年

0

像这样的正则

Sub test()
MsgBox KillChars("ABC-3.3%H14T-6")
End Sub

Function KillChars(strIn As String) As String
Dim objRegex
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "[^\w]+"
.Global = True
KillChars = .Replace(strIn, vbNullString)
End With
End Function
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.