简体   繁体   English

如何在工作表中搜索单词或短语?

[英]How to search a sheet for a word or phrase?

I'm writing the macro to search for a phrase, select the cell to the right, copy, select page 2 and then paste to a static cell there. 我正在编写宏来搜索短语,选择右边的单元格,复制,选择第2页,然后粘贴到那里的静态单元格。 The macro is for organizing restaurant sales reports on an Excel spreadsheet. 该宏用于在Excel电子表格上组织餐馆销售报告。

I'm new to programming and have no experience with VBA. 我是编程新手,没有VBA经验。

I cannot figure out how to search a sheet for a word or phrase. 我无法弄清楚如何在工作表中搜索单词或短语。

There are many ways to find a cell, it depends what you are trying to do. 有很多方法可以找到一个细胞,这取决于你想要做什么。

To do exactly what you are describing you would use the Range.Find method. 要完全按照您的描述进行操作,您将使用Range.Find方法。

Example of Range.Find Range.Find示例

In a new Workbook I write words such as cat and dog in random cells. 在一本新的练习册中,我在随机单元格中写下了猫和狗等词。

Then I create a new module with a public sub as such: 然后我创建一个带有public sub的新模块:

Public Sub TestFind()
  Sheet1.Cells _
    .Find("cat", LookIn:=xlValues, LookAt:=xlPart, MatchCase:=False) _
    .Offset(-1, 1) _
    .Copy Sheet2.[A1]
End Sub

Okay, to explain. 好的,解释一下。 If you aren't familiar, in VBA you can have named and optional arguments which I've used above. 如果您不熟悉,在VBA中,您可以使用我在上面使用的命名和可选参数 I've also used some line continuations or as microsoft calls them "line breaks" . 我也使用了一些行继续,或者微软称它们为“换行符”

Sheet1.Cells On Sheet1 I'm taking the Cells range (all the cells) and calling that range's Find method. Sheet1.Cells在Sheet1上我正在获取Cells范围(所有单元格)并调用该范围的Find方法。

.Find returns the first range containing the word cat anywhere in the cell (upper and lower case doesnt matter because of the MatchCase:=False , and LookAt:=xlPart means any part of the cell's contents, where LookAt:=xlWhole would mean the entire cell). .Find返回包含单词cat在单元格中任何位置的第一个范围(大小写无关紧要,因为LookAt:=xlPart MatchCase:=False ,而LookAt:=xlPart表示单元格内容的任何部分,其中LookAt:=xlWhole表示整个细胞)。

.Offset(-1,1) means get the range or cell one up and one to the right of the found cell. .Offset(-1,1)表示获取范围或单元格在找到的单元格中向上和向右一个。

.Copy Sheet2.[A1] the .[A1] syntax is the same as writing .Range("A1") . .Copy Sheet2.[A1] .[A1]语法与写.Range("A1") I hope it's obvious what this copy statement does. 我希望这个副本声明的作用很明显。

Other methods 其他方法

You could also look at doing something similar to a VLOOKUP or INDEX and MATCH. 您还可以查看类似于VLOOKUP或INDEX和MATCH的操作。 Or maybe use one of the sort or filter interfaces. 或者可以使用排序或过滤器接口之一。 It depends how your workbook is structured and what you want to do. 这取决于您的工作簿的结构以及您想要做的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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