Forum Discussion
Assistance Needed with VBA Code for Copying Data
- 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
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
Thank you very much! I implemented the changes you recommended, and now the code is successfully copying the data as needed. I truly appreciate your assistance!