2017-03-08 44 views
1

我想創建一個宏給我一些問題,因爲我沒有經驗,也不知道從哪裏開始。Excel FInd並替換正則表達式宏

我所要做的就是創建一個查找並替換宏,它將用空白替換部分字符串。

例如,我有以下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 
+1

「Id」是一個數字嗎? –

+0

Nope Id是一個字符串,另一個例子是'Custom field(Status)',我只想保留'Status' – dataMan

+0

,這樣我的Solution1就可以用於這兩種情況。你可以創建一個VBA代碼,用於查找並替換字符串自定義字段(用於'nothing'和''查找並替換''char')用於'Nothing' –

回答

1

你可以做到這一點使用Find & Replace沒有正則表達式!

enter image description here

解決方法1:

  1. 選擇數據
  2. 打開Find &更換模塊
  3. ""
  4. 更換"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 
+0

的問題感謝您的回答,這是非常有幫助的,但是我仍然有一個輕微的問題,當我運行宏沒有任何反應?我改變了你在代碼中找到替換建議,但正如我在運行時所說的那樣,沒有任何改變? – dataMan

+1

解決了這個問題,事實證明安全級別設置爲高,馬科斯被禁用,再次感謝 – dataMan

0

正則表達式/ 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