VBA Excel 宏查找文本并查找下一个相邻单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17412372/
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 21:59:47  来源:igfitidea点击:

VBA Excel Macro find text and find next adjacent cell

excelexcel-vbaexcel-formulaexcel-2010vba

提问by mgrobins

I'm trying to write a VBA Excel Macro to create an algorithm that will find text and find next adjacent cell to display text in a msgbox for example:

我正在尝试编写一个 VBA Excel 宏来创建一个算法,该算法将查找文本并查找下一个相邻单元格以在 msgbox 中显示文本,例如:

I parsed the sentence "The building has a broken pipe beneath the first floor." into separate cells. Using this code:

我解析了这句话“大楼一楼下面的管道坏了”。进入单独的单元格。使用此代码:

Sub Module3()
'
' Parse text
'

'
    Selection.TextToColumns Destination:=Range("A2"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, _
        Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
        Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1)), TrailingMinusNumbers:=True
End Sub

The sentence is now parsed. Once I select a cell how can I display the adjacent cell in a msgbox

句子现在被解析。选择一个单元格后,如何在 msgbox 中显示相邻的单元格

  1. Find Text “broken”
  2. Find text “broken” and adjacent word “pipe”
  1. 查找文本“broken”
  2. 查找文本“broken”和相邻的单词“pipe”

回答by Jon Crowell

This will do what you need:

这将做你需要的:

Sub FindPlusOffset()
    Dim ws As Worksheet
    Dim match As Range
    Dim findMe As String
    Dim findOffset As String

    Set ws = ThisWorkbook.Sheets("Sheet1")
    findMe = "broken"

    Set match = ws.Cells.Find(findMe)
    findOffset = match.Offset(, 1).Value
    MsgBox "The adjacent word to """ & findMe & """ is """ & findOffset & """."
End Sub

You'll probably want to add some error handling in case the word you are looking for isn't found. You can set the wsobject to whatever sheet name you are working with.

如果找不到您要查找的单词,您可能需要添加一些错误处理。您可以将ws对象设置为您正在使用的任何工作表名称。