通過正則表達式提取excel特定列中含有關鍵字的所有行數據
阿新 • • 發佈:2017-11-12
需要 bsp att 使用 sub sea ive nbsp end
在 Excel 中打開需要提取數據excel文件,使用 Alt+F11 快捷鍵打開 VBA 項目窗口,在左側的工作表名稱上點右鍵,選擇查看代碼,即可出現右側的編輯代碼窗口(如下圖)
在代碼窗口中輸入以下代碼:
1 Private Sub RegExp_GetNeedData() 2 3 Dim RegExp As Object 4 Dim SearchRange As Range, Cell As Range 5 6 ‘此處定義正則表達式 7 Set RegExp = CreateObject("vbscript.regexp")8 9 ‘需要重新定義的地方在這裏 10 keyword = "keyword" 11 n = 5 12 RangeVar = "D1:D100" 13 14 RegExp.Pattern = keyword 15 ‘此處指定查找範圍 16 Set SearchRange = ActiveSheet.Range(RangeVar) 17 Dim i As Integer 18 For i = 1 To n 19 Cells(1, n + i + 1) = Cells(1, i) 20 Next21 Line = 2 22 ‘遍歷查找範圍內的單元格 23 For Each Cell In SearchRange 24 cloumn = Cell.Column 25 Set Matches = RegExp.Execute(Cell.Value) 26 If Matches.Count >= 1 Then 27 Set Match = Matches(0) 28 Dim j As Integer 29 For j = 1 To n 30 Cells(Line, n + j + 1) = Cells(Cell.Row, j) 31 Next 32 Line = Line + 1 33 End If 34 Next 35 36 End Sub
根據需要可以替換掉keyword ,n, RangeVar;他們的意思分別是,需要匹配的關鍵字,表格數據列數,要匹配關鍵字的範圍;
通過正則表達式提取excel特定列中含有關鍵字的所有行數據