gpt4 book ai didi

vba - 如果找到(搜索词),则执行(操作)。如果没有,结束如果

转载 作者:行者123 更新时间:2023-12-04 21:15:57 26 4
gpt4 key购买 nike

如果你们能帮助我,那就太好了,因为它真的会帮助我。

这是我正在尝试做的事情:

  • 搜索具有特定术语的单元格
  • 如果找到,请复制单元格所在的整行并将其粘贴到其上方的一行中。
  • 如果没有找到,什么也不做,继续使用代码

  • 这是我的代码:
    Sub Test()
    '
    ' Test Macro
    '
    ' Keyboard Shortcut: Ctrl+b
    '

    Range("A5").Select
    Cells.Find(What:="PL 1", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Activate
    If Not IsEmpty(ActiveCell.Value) Then
    ActiveCell.Rows("1:1").EntireRow.Select
    Selection.Copy
    Range("A5").Select
    ActiveSheet.Paste
    End If
    Range("A5").Select
    Cells.Find(What:="PL 2", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Activate
    If Not IsEmpty(ActiveCell.Value) Then
    ActiveCell.Rows("1:1").EntireRow.Select
    Selection.Copy
    Range("A6").Select
    ActiveSheet.Paste
    End If
    Range("A5").Select
    Cells.Find(What:="PL 3", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Activate
    If Not IsEmpty(ActiveCell.Value) Then
    ActiveCell.Rows("1:1").EntireRow.Select
    Selection.Copy
    Range("A7").Select
    ActiveSheet.Paste
    End If
    End Sub

    我的代码仅在找到该值时才有效。如果未找到,则会出现以下错误: enter image description here

    最佳答案

    Cells.Find是一个返回 Range 的函数对象引用;当它没有找到任何东西时,引用将是 Nothing .而且你不能调用.ActivateNothing :

    This method returns Nothing if no match is found. The Find method does not affect the selection or the active cell. (MSDN)


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

    你需要重写你的代码和 避免 .Select 和 .Activate ,并避免使用 ActiveCell并隐含 ActiveSheet (您正在通过不使用适当的工作表引用来限定 Cells 调用)。

    由于以下几个原因,您的格式使代码难以阅读:
  • 在不同的行上指定了参数
  • 行延续被放置在任意位置
  • 嵌套成员调用未排队

  • 相比于:
    Cells.Find(What:="PL 2", After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False) _
    .Activate

    这只是可读性。问题是您基本上假设 .Find返回一个有效的对象引用。 不要假设,明确检查:
    Set result = Cells.Find(...)
    If Not result Is Nothing Then result.Activate

    但实际上,您需要想办法避免使用 .Select 和 .Activate。

    关于vba - 如果找到(搜索词),则执行(操作)。如果没有,结束如果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37550302/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com