[英]Excel : VBA Macro to extract keyword from cell containing string
我是Excel Macros和VBA的新手,並且面臨以下問題:
(1)我有一個約50,000行和11列的數據集。
(2)我需要基於某個關鍵字從工作表中提取行,該關鍵字與特定列中存在的字符串匹配。
(3)我有另一個堆棧溢出問題的以下代碼:
Sub testIt()
Dim r As Long, endRow as Long, pasteRowIndex As Long
endRow = 10 ' of course it's best to retrieve the last used row number via a function
pasteRowIndex = 1
For r = 1 To endRow 'Loop through sheet1 and search for your criteria
If Cells(r, Columns("B").Column).Value = "YourCriteria" Then 'Found
'Copy the current row
Rows(r).Select
Selection.Copy
'Switch to the sheet where you want to paste it & paste
Sheets("Sheet2").Select
Rows(pasteRowIndex).Select
ActiveSheet.Paste
'Next time you find a match, it will be pasted in a new row
pasteRowIndex = pasteRowIndex + 1
'Switch back to your table & continue to search for your criteria
Sheets("Sheet1").Select
End If
Next r
End Sub
(4)當正在搜索的列的單元格具有“ YourCriteria”作為唯一條目時,此方法可以很好地工作。
(5)但是,在我的數據中,我的字符串中嵌入了“ YourCriteria”
例如:“ YourCriteria” =“球”,並且特定列中的單元格包含“狗和球一起玩”,“球不好”等。
如何提取包含“ YourCriteria”的行?需要對代碼進行哪些修改?
謝謝
為了擴大道格的答案,
If InStr(Cells(r, 2).Value, "YourCriteria")>0 Then 'Found
' ^ Column A=1, B=2, ...
將更改2
編輯為要查找的任何列號(C = 3,D = 4,...)。 您也可以像以前一樣使用Columns("B").Column
,如果您對此更滿意的話。
我發現If InStr()>0
比If Instr()
更可靠,因為InStr
有很多返回值選項 。
為了避免將來出現問題,一般的想法是-而不是切換工作表,而是明確地指代您要指的工作表。 示例(未顯示所有代碼):
dim shSource as Sheet
set shSource = ActiveWorkbook.Sheets("Sheet1")
dim shDest as Sheet
set shDest = ActiveWorkbook.Sheets("Sheet2")
...
If InStr(shSource.Cells(r, 2).Value, "YourCriteria")>0 Then 'Found
shSource.Rows(r).Copy
shDest.Rows(pasteRowIndex).Select
shDest.Paste
VBA中有一個內置的運算符: Like 。 您可以使用以下命令替換當前測試:
If Cells(r, Columns("B").Column).Value Like "*YourCriteria*" Then 'Found
InStr( [start], string, substring, [compare] )
參數或參數
開始
可選的。 它是搜索的起始位置。 如果省略此參數,則搜索將從位置1開始。
串
要在其中搜索的字符串。
子串
您要查找的子字符串。
比較可選。 這是要執行的比較的類型。 它可以是以下值之一:
VBA常數值說明vbUseCompareOption -1使用選項比較vbBinaryCompare 0二進制比較vbTextCompare 1文本比較
最快的方法是:
range.Copy Sheets("Sheet2").Range("A1")
將數據直接復制到Sheet2 Sub DoIt() Dim SearchRange As Range Sheets("Sheet1").UsedRange.AutoFilter Field:=2, Criteria1:="=*Ball*", _ Operator:=xlAnd Set SearchRange = Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeVisible) If Not SearchRange Is Nothing Then SearchRange.Copy Sheets("Sheet2").Range("A1") End If End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.