需要仅使用给定代码在特定工作表中搜索单词

时间:2014-02-20 12:47:30

标签: excel vba excel-vba

Sub Example()
 Dim strFind As String
   Dim wks As Worksheet
   Dim rngFound As Range
   Dim CellNo As String
   Dim Data As String

   strFind = InputBox(prompt:="Enter string to find", Title:="Find what?")
   If Len(strFind) > 0 Then
      For Each wks In ActiveWorkbook.Worksheets
         Set rngFound = wks.UsedRange.Find(what:=strFind, LookIn:=xlValues, lookat:=xlPart, MatchCase:=False)
         If Not rngFound Is Nothing Then
            Application.Goto rngFound, True
              CellNo = rngFound.Address(Offset, Offset)
         End If
      Next wks
   '   MsgBox strFind & " not found."
   End If
End Sub

上面的代码用于在excel工作簿上搜索某些单词,并显示它最后找到的单词。

例如:如果我们在工作表1和工作表2中有名称“Cat”。因此,此代码有助于仅在工作表2中显示Cat而不显示工作表1。

所以现在我想做的是,我想选择表格。所以它必须只搜索所选的工作表。 如果我们要求它采用sheet1,它必须只从表1中搜索cat。它不应该再转到sheet2。

注意:必须根据工作表名称进行搜索。 如果我们给出Sheet2,它必须仅在工作表2上搜索cat。因此提供了工作表名称。

我尝试了几次实验,它显示了类型不匹配,需要对象。

任何只能帮助我修改这方面的事。

2 个答案:

答案 0 :(得分:0)

删除循环并更改所需值的周期 http://www.techrepublic.com/blog/10-things/10-ways-to-reference-excel-workbooks-and-sheets-using-vba/

Dim ws As Worksheet
Set ws = ActiveSheet

答案 1 :(得分:0)

您应该更改此部分代码:

  'For Each wks In ActiveWorkbook.Worksheets
     Set rngFound = ActiveSheet.UsedRange.Find(what:=strFind, LookIn:=xlValues, lookat:=xlPart, MatchCase:=False)
     If Not rngFound Is Nothing Then
        Application.Goto rngFound, True
          CellNo = rngFound.Address(Offset, Offset)
     End If
  'Next wks

您只需要删除循环并将rngFound更改为仅在ActiveSheet中查找。