我正在尝试创建一个宏,它给我一些问题,因为我没有经验,也不知道从哪里开始。
我要做的就是创建一个查找和替换宏,它将替换一部分字符串。
例如,我有以下Custom Field(Id)
,我希望marco做的就是删除Id
以外的所有内容。
我怎样才能做到这一点?
代码
Sub FindReplace()
Dim sht As Worksheet
Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long
fndList = Array("Custom field(", ")")
rplcList = Array("", "")
'Loop through each item in Array lists
For x = LBound(fndList) To UBound(fndList)
'Loop through each worksheet in ActiveWorkbook
For Each sht In ActiveWorkbook.Worksheets
sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
SearchFormat:=False, ReplaceFormat:=False
Next sht
Next x
End Sub
答案 0 :(得分:1)
您可以使用Find & Replace
而无需正则表达式来实现此目的。
<强>解决方法1:强>
"Custom Field("
""
")"
""
醇>
<强>溶液2:强>
您可以使用this site中的公式或使用this site处发布的VBA代码删除字符串中的所有非数字字符。
Sub RemoveNotNum()
'Updateby20131129
Dim Rng As Range
Dim WorkRng As Range
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
For Each Rng In WorkRng
xOut = ""
For i = 1 To Len(Rng.Value)
xTemp = Mid(Rng.Value, i, 1)
If xTemp Like "[0-9]" Then
xStr = xTemp
Else
xStr = ""
End If
xOut = xOut & xStr
Next i
Rng.Value = xOut
Next
End Sub
答案 1 :(得分:0)
Regexp / Variant数组解决方案
还处理用户选择范围内多个区域的情况。
Sub Retain()
Dim X
Dim rng1 As Range
Dim rng2 As Range
Dim objRegex As Object
Dim lngRow As Long
Dim lngCOl As Long
On Error Resume Next
Set rng1 = Application.InputBox("select range", , Selection.Address, , , , , 8)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.Pattern = "[^0-9]"
.Global = True
For Each rng2 In rng1.Areas
If rng2.Cells.Count > 1 Then
X = rng2.Value2
For lngRow = 1 To UBound(X, 1)
For lngCOl = 1 To UBound(X, 2)
X(lngRow, lngCOl) = .Replace(X(lngRow, lngCOl), vbNullString)
Next
Next
rng2.Value2 = X
Else
rng2.Value2 = .Replace(rng2, vbNullString)
End If
Next
End With
End Sub