简体   繁体   English

VBA文本搜索范围,然后运行宏

[英]VBA Search Range for text then run macro

I'm trying to write a VBA macro (which I'll attach to a command button) which searches K7 through K13 to find "Sheet1", "Sheet2", "Sheet3", or "Sheet4" Only one answer is possible based on pre-existing If/Then statements. 我正在尝试编写一个VBA宏(我将其附加到命令按钮),该宏通过K13搜索K7以找到“ Sheet1”,“ Sheet2”,“ Sheet3”或“ Sheet4”。预先存在的If / Then语句。 When it finds "Sheet1" I want it to run macro "GoToSheet1" When it finds "Sheet2" I want it to run macro "GoToSheet2" When it finds "Sheet3" I want it to run macro "GoToSheet3" When it finds "Sheet4" I want it to run macro "GoToSheet4" 当它找到“ Sheet1”时,我希望它运行宏“ GoToSheet1”。当它找到“ Sheet2”时,我希望它运行宏“ GoToSheet2”。当它找到“ Sheet3”时,我希望它运行宏“ GoToSheet3”。当它找到“ Sheet4”时, “我希望它运行宏“ GoToSheet4”

Basically i have four possible conditions which could exist based on how someone answers two yes/no questions. 基本上,根据某人回答两个是/否问题的方式,我可能存在四个可能的条件。 That is what the initial if/then statements cover. 这就是最初的if / then语句所涵盖的内容。 However, I cannot get the VBA macro to search across the cell range K7 through K13 for any one of the four text phrases. 但是,我无法使VBA宏在单元格范围K7到K13内搜索四个文本短语中的任何一个。

Surely you can loop thru the range K7:K13 for checking each cell values. 当然,您可以遍历范围K7:K13来检查每个单元格的值。 However using Range.Find method would be a better way to do this. 但是,使用Range.Find方法将是一种更好的方法。

Private Sub CommandButton1_Click()
    Dim lookingRange As Range
    Set lookingRange = Range("K7:K13")
    If Not lookingRange.Find(What:="Sheet1", LookIn:=xlValues) Is Nothing Then GoToSheet1: Exit Sub
    If Not lookingRange.Find(What:="Sheet2", LookIn:=xlValues) Is Nothing Then GoToSheet2: Exit Sub
    If Not lookingRange.Find(What:="Sheet3", LookIn:=xlValues) Is Nothing Then GoToSheet3: Exit Sub
    If Not lookingRange.Find(What:="Sheet4", LookIn:=xlValues) Is Nothing Then GoToSheet4: Exit Sub
    MsgBox "not found"
End Sub

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

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