简体   繁体   English

Excel:VBA宏从包含字符串的单元格中提取关键字

[英]Excel : VBA Macro to extract keyword from cell containing string

I am new to Excel Macros and VBA, and am facing the following problem: 我是Excel Macros和VBA的新手,并且面临以下问题:

(1) I have a data-set which has ~50,000 rows and 11 columns. (1)我有一个约50,000行和11列的数据集。

(2) I need to extract rows from the sheet, based on a certain keyword - which matches the strings present in a particular column. (2)我需要基于某个关键字从工作表中提取行,该关键字与特定列中存在的字符串匹配。

(3) I have the following code from another stack overflow question: (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) This works perfectly fine when the cell of the column being searched has "YourCriteria" as the only entry. (4)当正在搜索的列的单元格具有“ YourCriteria”作为唯一条目时,此方法可以很好地工作。

(5) However, in my data I have strings which have the "YourCriteria" embedded in them (5)但是,在我的数据中,我的字符串中嵌入了“ YourCriteria”

For Example: "YourCriteria" = "ball" and the cell(s) in a particular column contain "the dog plays with the ball" , "the ball is bad" etc. 例如:“ YourCriteria” =“球”,并且特定列中的单元格包含“狗和球一起玩”,“球不好”等。

How can I extract the rows containing 'YourCriteria" ? What modification to the code is needed ? 如何提取包含“ YourCriteria”的行?需要对代码进行哪些修改?

Thanks 谢谢

To expand on Doug's answer, 为了扩大道格的答案,

If InStr(Cells(r, 2).Value, "YourCriteria")>0 Then 'Found
               '  ^ Column A=1, B=2, ...

Edit Change 2 to whatever column number you want to look in (C=3, D=4, ...). 更改2 编辑为要查找的任何列号(C = 3,D = 4,...)。 You can also use Columns("B").Column like you had it, if you're more comfortable with that. 您也可以像以前一样使用Columns("B").Column ,如果您对此更满意的话。

I have found If InStr()>0 to be more reliable than If Instr() since InStr has lots of return-value options . 我发现If InStr()>0If Instr()更可靠,因为InStr很多返回值选项

A general thought, to avoid future problems - rather than switching sheets, refer expressly to which sheet you mean. 为了避免将来出现问题,一般的想法是-而不是切换工作表,而是明确地指代您要指的工作表。 Example (not all code shown): 示例(未显示所有代码):

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

There's a built in operator for this in VBA: Like . VBA中有一个内置的运算符: Like You can just replace the current test with this: 您可以使用以下命令替换当前测试:

If Cells(r, Columns("B").Column).Value Like "*YourCriteria*" Then 'Found
InStr( [start], string, substring, [compare] )

Parameters or Arguments 参数或参数

start 开始

Optional. 可选的。 It is the starting position for the search. 它是搜索的起始位置。 If this parameter is omitted, the search will begin at position 1. 如果省略此参数,则搜索将从位置1开始。

string

The string to search within. 要在其中搜索的字符串。

substring 子串

The substring that you want to find. 您要查找的子字符串。

compare Optional. 比较可选。 It is the type of comparison to perform. 这是要执行的比较的类型。 It can be one of the following values: 它可以是以下值之一:

VBA Constant Value Explanation vbUseCompareOption -1 Uses option compare vbBinaryCompare 0 Binary comparison vbTextCompare 1 Textual comparison VBA常数值说明vbUseCompareOption -1使用选项比较vbBinaryCompare 0二进制比较vbTextCompare 1文本比较

borrowed from http://www.techonthenet.com/excel/formulas/instr.php http://www.techonthenet.com/excel/formulas/instr.php借来的

The fastest way is to: 最快的方法是:

  • Apply a Filter to the data 将过滤器应用于数据
  • Set a range variable = .SpecialCells(xlCellTypeVisible) 设置范围变量= .SpecialCells(xlCellTypeVisible)
  • Use range.Copy Sheets("Sheet2").Range("A1") to copy the data straight to Sheet2 使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM