Forum Discussion

AKuma0411's avatar
AKuma0411
Brass Contributor
Dec 02, 2024
Solved

Assistance Needed with VBA Code for Copying Data

Hi, I'm seeking help with a VBA code I've implemented to copy data from the "By Facility" tab to the "CS_export" tab. The code functions correctly when there are multiple line items in the "By Facil...
  • HansVogelaar's avatar
    Dec 02, 2024

    All parts that look like this:

    .Range("G4", Range("G" & Rows.count)

    should be changed to

    .Range("G4", .Range("G" & .Rows.count)

    Declare a new variable

    Dim rngCopy As Range

    Change all sets of lines like this:

    .Range("G5", .Range("G" & .Rows.count).End(xlUp)).SpecialCells(xlCellTypeVisible).Copy
    wbMaster.Worksheets("CS_Export").Range("L2").PasteSpecial xlPasteValues

    to

    Set rngCopy = .Range("G5", .Range("G" & .Rows.count).End(xlUp))
    If rngCopy.Count > 1 Then
        Set rngCopy = rngcopy.SpecialCells(xlCellTypeVisible)
    End If
    rngCopy.Copy
    wbMaster.Worksheets("CS_Export").Range("L2").PasteSpecial xlPasteValues

    P.S. The code refers to a worksheet OS that is not present in the workbook that you attached.

    The macro should end like this, so that ScreenUpdating and DisplayAlerts are set even if an error occurs. (Why do you want to set DisplayAlerts to False at the end, by the way?)

    Exit_handler:
        With Application
            .ScreenUpdating = True
            .DisplayAlerts = False
        End With
        Exit Sub
    
    Error_handler:
        MsgBox "An error has occured while processing the file. Please close the file and rerun it, if the problem persists contact the CE support team"
        Application.Calculation = xlAutomatic
        Resume Exit_handler
    End Sub

Resources