【问题标题】:Excel/vba: How to skip to next sheet if error?Excel/vba:如果出错,如何跳到下一张?
【发布时间】:2020-01-04 14:23:18
【问题描述】:

我正在尝试从每个工作表中查找“HFM”,如果有的话,在此之后粘贴一些名称。那么问题是当工作表中没有“HFM”时如何避免将名称添加到工作表中?

我首先有没有On Error Resume Next的代码,但随后出现了运行时错误。添加时,它会将名称复制到所有工作表。如果从没有“HFM”的工作表开始,它也会返回运行时错误。那么我该如何解决呢?


Dim ws As Worksheet

For Each ws In Worksheets


    Cells.Find(What:="HFM", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
        xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
        , SearchFormat:=False).Activate

    On Error Resume Next



    ActiveCell.Offset(0, 3).Select

    ActiveCell.FormulaR1C1 = "name1"

' etc. 

【问题讨论】:

  • 将Find方法的结果设置为一个变量,然后再检查是否是Nothing - 不惜一切代价避免使用On Error Resume Next。

标签: excel vba


【解决方案1】:

而不是 On Error Resume 接下来,您必须根据结果声明一个变量继续。下面是一个例子。

Dim ws As Worksheet

    For Each ws In Worksheets
    ' Search for a text
    Set MyObjectvie = ws.Cells.Find(What:="HFM", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
            xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
            , SearchFormat:=False)

        If Not MyObjectvie Is Nothing Then
            ' if the text is found do the task
            MyObjectvie.Offset(0, 3).Value = "name1"
        End If

    Next ws

【讨论】:

  • 谢谢,这行得通,但它只适用于一张纸。如何让它在所有工作表上运行?
  • @user12646795 我已经相应地修改了代码。这行得通。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 2019-04-21
  • 2020-05-28
相关资源
最近更新 更多