excel 使用“查找”工具后选择单元格

ovfsdjhp  于 2023-10-22  发布在  其他
关注(0)|答案(3)|浏览(156)

尝试在使用查找工具后选择单元格,但不起作用。
你好
我的计划是,从第一个单元格开始,找到一个带有“b1 -”的单元格,选择它,向右偏移11个单元格,然后选择其中的4x 4正方形,并复制它。我现在有这个,它不工作。错误是424,“强制对象”

Sub Macro4()
'
' Macro4 Macro
'
' Atalho do teclado: Ctrl+a
'
    Range("A1").Select
    Cells.Find(What:="b1 -", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate
    Cell.Select
    ActiveCell.Offset(0, 11).Range("A1:B4").Select
    Selection.Copy
End Sub

任何帮助都非常感谢

0mkxixxg

0mkxixxg1#

试试这个。当使用Find时,首先检查值是否找到总是好的,否则你将有一个错误要处理。

Sub Macro4()

Dim r As Range

Set r = Cells.Find(What:="b1 -", After:=Range("A1"), LookIn:=xlFormulas, _
                   LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                   MatchCase:=False, SearchFormat:=False)
If Not r Is Nothing Then 'check found first
    r.Offset(0, 11).Resize(2, 2).Select
    'no need to select, i.e. just "r.Offset(0, 11).Resize(2, 2).copy" is better
End If

End Sub

此外,选择的东西是不可取的-How to avoid using Select in Excel VBA

hmae6n7t

hmae6n7t2#

根据找到的单元格引用范围

Sub Macro4()
'
' Macro4 Macro
'
' Atalho do teclado: Ctrl+a
'
    
    Const FIRST_CELL_IN_COLUMN As String = "A2"
    Const CONTAINS As String = "b1 -"
    Const COLUMN_OFFSET As Long = 11
    Const SIZE_ROWS As Long = 4
    Const SIZE_COLS As Long = 4
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    Dim prg As Range, fCell As Range
    
    With ws.Range(FIRST_CELL_IN_COLUMN)
        Set prg = .Resize(ws.Rows.Count - .Row + 1)
        With prg
            Set fCell = .Find(CONTAINS, .Cells(.Cells.Count), xlFormulas, xlPart)
        End With
    End With
    
    If fCell Is Nothing Then
        MsgBox "The string """ & CONTAINS & """ is not contained in any cell " _
            & "of the range """ & prg.Address(0, 0) & """ of worksheet """ _
            & ws.Name & """!", vbExclamation
        Exit Sub
    End If
    
    Dim rg As Range:
    Set rg = fCell.Offset(, COLUMN_OFFSET).Resize(SIZE_ROWS, SIZE_COLS)
    
    Debug.Print fCell.Address(0, 0), rg.Address(0, 0)
    
    rg.Copy
    
End Sub
xhv8bpkk

xhv8bpkk3#

你就快成功了这里有一些调整给你。:)

Sub Test()
    Cells.Find(What:="b1 -", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Offset(0, 11).Range("A1:B4").Copy
End Sub

相关问题