Search code examples
excelvbasearcherror-correction

Search a copied value MACRO


I have two sheets:

  1. Database

  2. Macro sheet: It has a row with dates that will be the headings of a table after the macro.

Objective: In the macro sheet take the value of the first date and look for its position in the database sheet. Then, in the database sheet, copy the entire column corresponding to the previously copied date.

I understand that the code should look something like this:

    Sheets("Macro").Select
    Range("K3").Select
    Selection.Copy
    Sheets("Database").Select
    Cells.Find(What:=Selection.PasteSpecial xlValues, After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Activate
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Sheets("Macro").Select
    ActiveSheet.Paste

This code does not work, because the search part is not done well, I will appreciate some correction


Solution

  • Something along these lines.

    Read this to learn the advantages of not using Select or Activate.

    When using Find, always check first that your search term is found to avoid an error. For example, you cannot activate a cell that does not exist.

    Sub x()
    
    Dim r As Range
    
    With Sheets("Database")
        Set r = .Cells.Find(What:=Sheets("Macro").Range("K3").Value, lookAt:=xlPart, _
                            SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                            MatchCase:=False, SearchFormat:=False)
        If Not r Is Nothing Then
            Range(r, r.End(xlDown)).Copy Sheets("Macro").Range("A1")
        End If
    End With
    
    End Sub