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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18361146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 22:53:02  来源:igfitidea点击:

How to search a sheet for a word or phrase?

excelvba

提问by Smoore

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. The macro is for organizing restaurant sales reports on an Excel spreadsheet.

我正在编写宏来搜索一个短语,选择右侧的单元格,复制,选择第 2 页,然后粘贴到那里的静态单元格。该宏用于在 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.

我不知道如何在工作表中搜索单词或短语。

回答by AndASM

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.Findmethod.

要完全按照您的描述进行操作,您将使用该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 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 argumentswhich I've used above. I've also used some line continuations or as microsoft calls them "line breaks".

好吧,解释一下。如果您不熟悉,在 VBA 中,您可以使用我上面使用的命名参数和可选参数。我还使用了一些换行符,或者微软称之为“换行符”

Sheet1.CellsOn Sheet1 I'm taking the Cells range (all the cells) and calling that range's Find method.

Sheet1.Cells在 Sheet1 上,我使用 Cells 范围(所有单元格)并调用该范围的 Find 方法。

.Findreturns the first range containing the word cat anywhere in the cell (upper and lower case doesnt matter because of the MatchCase:=False, and LookAt:=xlPartmeans any part of the cell's contents, where LookAt:=xlWholewould mean the entire cell).

.Find返回包含单元格中任何位置的单词 cat 的第一个范围(大小写无关紧要,因为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"). I hope it's obvious what this copy statement does.

.Copy Sheet2.[A1].[A1]语法与write 相同.Range("A1")。我希望这份副本声明的作用很明显。

Other methods

其他方法

You could also look at doing something similar to a VLOOKUP or INDEX and MATCH. Or maybe use one of the sort or filter interfaces. It depends how your workbook is structured and what you want to do.

您还可以考虑执行类似于 VLOOKUP 或 INDEX 和 MATCH 的操作。或者可能使用排序或过滤器接口之一。这取决于您的工作簿的结构以及您想要做什么。