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

时间:2017-11-21 05:33:16

标签: excel vba excel-vba

我试图写一个VBA宏(我将附加到一个命令按钮),它搜索K7到K13以找到" Sheet1"," Sheet2&#34 ;," Sheet3",或" Sheet4"根据预先存在的If / Then语句,只能有一个答案。 当它找到" Sheet1"我想让它运行宏" GoToSheet1" 当它找到" Sheet2"我想让它运行宏" GoToSheet2" 当它找到" Sheet3"我想让它运行宏" GoToSheet3" 当它找到" Sheet4"我希望它能够运行宏" GoToSheet4"

基本上我有四种可能存在的条件,这些条件可能基于某人如何回答两个是/否问题。这就是最初的if / then语句涵盖的内容。但是,我无法让VBA宏在单元格范围K7到K13中搜索四个文本短语中的任何一个。

1 个答案:

答案 0 :(得分:0)

当然,您可以循环通过范围K7:K13来检查每个单元格值。但是,使用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