Thanks in advance for helping!
I am currently using the below code to populate multiple .csv files into one sheet and then hide the sheet. The help I need is to remove duplicate rows from that sheet. Can it be incorporated into this code? Thank you!
Sub ImportCSVsWithReference()
'UpdatedforSPSS
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select the folder with the csv files [File Picker]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = Sheets.Add
ActiveSheet.Name = "ImportedData"
Worksheets("ImportedData").Visible = False
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\" & "*.csv")
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
ActiveSheet.UsedRange.Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
xWb.Close False
xFile = Dir
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "Encountered an error. Try again", , "Error"
End Sub
There is actually a built-in function to remove duplicates from a range. It is called RemoveDuplicates...
Let's look at an example. I assume here that -
The table has 3 columns
The table has 100 rows
The table does not have a header line
Then the code to remove duplicates will look something like:
ActiveSheet.Range("A1:C100").RemoveDuplicates Columns:=Array(1, 2, 3), Header:=xlNo
See the docs at https://learn.microsoft.com/en-us/office/vba/api/excel.range.removeduplicates
Do Not Import Headers After the First Imported Worksheet
s - Source (read from)
d - Destination (written to)
The Code
Option Explicit
Sub ImportCSVsWithReference()
Const ProcName As String = "ImportCSVsWithReference"
'On Error GoTo clearError
Const WorksheetName As String = "ImportedData"
Const HeaderRows As Long = 1
' Get Folder Path.
Dim FolderPath As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
With fd
.AllowMultiSelect = False
'.InitialFileName = "C:\Test" ' consider using this
.Title = "Select the folder with the csv files [File Picker]"
If .Show = -1 Then
FolderPath = .SelectedItems(1)
Else
GoTo ProcExit ' Exit Sub
End If
End With
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Application.ScreenUpdating = False
' Define Destination Worksheet (delete existing, add new).
On Error Resume Next
Dim dws As Worksheet: Set dws = dwb.Worksheets(WorksheetName)
On Error GoTo 0
If Not dws Is Nothing Then ' it already exists
Application.DisplayAlerts = False
dws.Delete ' delete without confirmation
Application.DisplayAlerts = True
End If
Set dws = dwb.Worksheets.Add(After:=dwb.Sheets(dwb.Sheets.Count)) ' Sheets!
dws.Name = WorksheetName
dws.Visible = xlSheetHidden ' xlSheetVeryHidden (a 'tougher' option)
' Define Destination Cell.
Dim dCell As Range: Set dCell = dws.Range("A1")
' Copy data from Source Worksheets to Destination Worksheet.
Dim FileName As String: FileName = Dir(FolderPath & "\" & "*.csv")
Dim sws As Worksheet
Dim srg As Range
Dim swsCount As Long
Do While FileName <> ""
' There is only one worksheet in a csv file (the first):
Set sws = Workbooks.Open(FolderPath & "\" & FileName).Worksheets(1)
Set srg = sws.UsedRange
If srg.Rows.Count > HeaderRows Then
swsCount = swsCount + 1
If swsCount > 1 Then ' headers for the first worksheet only
Set srg = srg.Resize(srg.Rows.Count - HeaderRows) _
.Offset(HeaderRows)
End If
dCell.Resize(srg.Rows.Count, srg.Columns.Count).Value _
= srg.Value
Set dCell = dCell.Offset(srg.Rows.Count)
End If
sws.Parent.Close False ' the workbook is the 'parent' of the worksheet
FileName = Dir
Loop
'dwb.save
ProcExit:
If Application.ScreenUpdating = False Then
Application.ScreenUpdating = True
End If
' Inform.
Select Case swsCount
Case 0
MsgBox "No worksheet imported.", vbExclamation, "Fail?"
Case 1
MsgBox "1 worksheet imported.", vbInformation, "Success"
Case Else
MsgBox swsCount & " worksheets imported.", vbInformation, "Success"
End Select
Exit Sub
clearError:
MsgBox "'" & ProcName & "': Unexpected Error!" & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Sub
Related
i'm having a bit of a headache with VBA which i haven't used since 2006.
I have my destination excel file where I need to import 3 predefined sheets from another excel file of the user's choice.
After selecting the source file to import I would like to perform a check, IF the "Cover" sheet exists THEN copy it to the target workbook ELSE print an error message in the excel file in order to have a log, once this is done I have to do the same check for the "Functional" and "Batch" sheets.
Before inserting the IFs, I was able to import the sheets but I didn't have control over whether they existed or not, "Cover" is mandatory while "Functional" and "Batch" I need at least one of the two to be able to proceed with the next steps.
Now I can check if the "Cover" sheet exists and import it ELSE I exit the Sub, after which I should check if the other sheets also exist and import them but I immediately get the "absent sheet" error.
Below is the code I am getting stuck with:
Sub Import()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim TargetWorkbook As Workbook
Dim SourceWorkbook As Workbook
Dim OpenFileName
Set TargetWorestBookkbook = ActiveWorkbook
'Select and Open Source workbook
OpenFileName = Application.GetOpenFilename("Excel Files (*.xls*),*.xls*")
If OpenFileName = False Then
MsgBox "Nessun file Source selezionato. Impossibile procedere."
Exit Sub
End If
On Error GoTo exit_
Set SourceWorkbook = Workbooks.Open(OpenFileName)
'Import sheets
' if the sheet doesn't exist an error will occur here
If WorksheetExists("Cover e Legenda") Then
SourceWorkbook.Sheets("Cover e Legenda").Copy _
after:=TargetWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Application.CutCopyMode = False
SourceWorkbook.Close False
Else
MsgBox ("Cover assente. Impossibile proseguire.")
Exit Sub
End If
If WorksheetExists("Test Funzionali") Then
SourceWorkbook.Sheets("Test Funzionali").Copy _
after:=TargetWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Application.CutCopyMode = False
SourceWorkbook.Close False
Else
MsgBox ("Test Funzionali assente.")
End If
If WorksheetExists("Test Batch") Then
SourceWorkbook.Sheets("Test Batch").Copy _
after:=TargetWorkbook.Sheets(ThisWorkbook.Sheets.Count)
Application.CutCopyMode = False
SourceWorkbook.Close False
Else
MsgBox ("Test Batch assente.")
End If
'Next Sheet
Application.ScreenUpdating = True
Application.DisplayAlerts = True
SourceWorkbook.Close SaveChanges:=False
MsgBox ("Importazione completata.")
TargetWorkbook.Activate
exit_:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
If Err Then MsgBox Err.Description, vbCritical, "Error"
End Sub
Best to check all of the sheets before importing any of them.
Try something like this:
Sub Import()
Dim wbTarget As Workbook, wbSource As Workbook
Dim OpenFileName, haveCover As Boolean, haveFunz As Boolean, haveTest As Boolean
On Error GoTo haveError
Set wbTarget = ActiveWorkbook
'Select and Open Source workbook
OpenFileName = Application.GetOpenFilename("Excel Files (*.xls*),*.xls*")
If OpenFileName = False Then
MsgBox "Nessun file Source selezionato. Impossibile procedere."
Exit Sub
End If
Set wbSource = Workbooks.Open(OpenFileName)
'check which sheets exist
haveCover = WorksheetExists(wbSource, "Cover e Legenda")
haveFunz = WorksheetExists(wbSource, "Test Funzionali")
haveTest = WorksheetExists(wbSource, "Test Batch")
If haveCover And (haveFunz Or haveTest) Then 'have the minumum required sheets?
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ImportSheet wbTarget, wbSource.Worksheets("Cover e Legenda")
If haveFunz Then ImportSheet wbTarget, wbSource.Worksheets("Test Funzionali")
If haveTest Then ImportSheet wbTarget, wbSource.Worksheets("Test Batch")
Application.DisplayAlerts = True
Else
MsgBox "Required sheet(s) not found!", vbExclamation
End If
wbSource.Close SaveChanges:=False
MsgBox "Importazione completata"
wbTarget.Activate
Exit Sub 'normal exit
haveError:
MsgBox Err.Description, vbCritical, "Error"
Application.DisplayAlerts = True
End Sub
'copy sheet `ws` to the end of `wbTarget`
Sub ImportSheet(wbTarget As Workbook, ws As Worksheet)
ws.Copy after:=wbTarget.Worksheets(wbTarget.Worksheets.Count)
End Sub
'does sheet `wsName` exist in workbook `wb` ?
Function WorksheetExists(wb As Workbook, wsName As String) As Boolean
On Error Resume Next
WorksheetExists = Not wb.Worksheets(wsName) Is Nothing
On Error GoTo 0
If Not WorksheetExists Then
'log error to errors sheet
With ThisWorkbook.Worksheets("Import Errors").Cells(Rows.Count, "A").End(xlUp)
.Resize(1, 3).Value = Array(Now, wb.Name, "Sheet '" & wsName & "' not found")
End With
End If
End Function
Import Mandatory and Optional Worksheets
Sub ImportWorksheets()
Dim Mandatory() As Variant: Mandatory = VBA.Array("Cover e Legenda")
Dim Optionally() As Variant ' 'Optional' is a keyword
Optionally = VBA.Array("Test Funzionali", "Test Batch")
Dim twb As Workbook: Set twb = ThisWorkbook ' workbook containing this code
' Select and open the Source workbook.
Dim OpenFilePath As Variant
OpenFilePath = Application.GetOpenFilename("Excel Files (*.xls*),*.xls*")
If OpenFilePath = False Then
MsgBox "Nessun file Source selezionato. Impossibile procedere.", _
vbExclamation
Exit Sub
End If
Dim swb As Workbook: Set swb = Workbooks.Open(OpenFilePath)
' Check if all the mandatory worksheets exist.
Dim sws As Worksheet, n As Long
For n = 0 To UBound(Mandatory)
On Error Resume Next ' prevent error if worksheet doesn't exist
Set sws = swb.Worksheets(Mandatory(n))
On Error GoTo 0
If sws Is Nothing Then
'swb.Close SaveChanges:=False
MsgBox "The mandatory worksheet """ & Mandatory(n) _
& """ was not found in """ & swb.Name & """.", vbCritical
Exit Sub
Else
Set sws = Nothing
End If
Next n
' Check if at least one of the optional worksheets exists.
Dim oDict As Object: Set oDict = CreateObject("Scripting.Dictionary")
oDict.CompareMode = vbTextCompare
For n = 0 To UBound(Optionally)
On Error Resume Next ' prevent error if worksheet doesn't exist
Set sws = swb.Worksheets(Optionally(n))
On Error GoTo 0
If Not sws Is Nothing Then oDict(sws.Name) = Empty: Set sws = Nothing
Next n
If oDict.Count = 0 Then
'swb.Close SaveChanges:=False
MsgBox "No optional worksheets found in """ & swb.Name & """.", _
vbCritical
Exit Sub
End If
' Import the worksheets and close the Source workbook.
Application.ScreenUpdating = False
For n = 0 To UBound(Mandatory)
swb.Sheets(Mandatory(n)).Copy After:=twb.Sheets(twb.Sheets.Count)
Next n
Dim oKey As Variant
For Each oKey In oDict.Keys
swb.Sheets(oKey).Copy After:=twb.Sheets(twb.Sheets.Count)
Next oKey
swb.Close SaveChanges:=False
Application.ScreenUpdating = True
' Inform.
MsgBox "Imported Worksheets" & vbLf & vbLf _
& "Mandatory:" & vbLf & Join(Mandatory, vbLf) & vbLf & vbLf _
& "Optionally:" & vbLf & Join(oDict.Keys, vbLf), vbInformation
End Sub
I need a macro that can copy the entire row from the workbook I am in based on the cell I have selected. I can do this already, using the following:
ActiveCell.EntireRow.Select
Selection.Copy
But then, I need it to paste that (formatting and all) into the first empty row (based on column B) of a workbook that is closed. R:\dasboards\wo.xlsm
Backup Entire Row to a Closed Workbook
Adjust the values in the constants section.
Option Explicit
Sub BackupEntireRow()
Const dFilePath As String = "R:\DashBoards\wo.xlsm"
Const dwsName As String = "Sheet1"
Const dlrCol As String = "B"
Dim IsSuccess As Boolean
If TypeName(Selection) <> "Range" Then
MsgBox "No cells selected.", vbCritical
Exit Sub
End If
Dim dwbName As String: dwbName = Dir(dFilePath)
If Len(dwbName) = 0 Then
MsgBox "Could not find the destination file" _
& vbLf & "'" & dFilePath & "'", vbCritical
Exit Sub
End If
Dim srrg As Range: Set srrg = ActiveCell.EntireRow
Dim dwb As Workbook
Dim dDoCloseWorkbook As Boolean
On Error Resume Next
Set dwb = Workbooks(dwbName)
On Error GoTo 0
If dwb Is Nothing Then
Set dwb = Workbooks.Open(dFilePath)
dDoCloseWorkbook = True
End If
Dim dws As Worksheet
On Error Resume Next
Set dws = dwb.Worksheets(dwsName)
On Error GoTo 0
If dws Is Nothing Then
If dDoCloseWorkbook Then
dwb.Close SaveChanges:=False
End If
MsgBox "The destination worksheet '" & dwsName & "' doesn't exist.", _
vbCritical
Exit Sub
End If
Dim dCell As Range
Set dCell = dws.Cells(dws.Rows.Count, dlrCol).End(xlUp).Offset(1)
Dim drrg As Range: Set drrg = dCell.EntireRow
srrg.Copy drrg
If dDoCloseWorkbook Then
dwb.Close SaveChanges:=True
Else
dwb.Save
End If
IsSuccess = True
If IsSuccess Then
MsgBox "Row backed up.", vbInformation
End If
End Sub
I'm trying to write a small code in Excel that lets me open in the background another workbook, copy a range of data in there, and then pasty it in the active workboo. Should be pretty straight forward but for some reason I'm getting this error. So far what I've got is this, and I know the error comes from this line "cpyLastRow = ImportBook.cpySheet.Cells(3, 1).End(xlDown).Row", Ive got some variables commented to make it a little bit mor dyanimc in the future. Any ideas?
Private Sub CommandButton2_Click()
Dim OpenFile As Variant
Dim ImportBook As Workbook
Dim cpySheet As Worksheet
Dim cpyLastRow As Long
Dim cpyLastColumn As Long
'Dim cpyStartCell As Range
Set cpySheet = Sheets("DAO")
'Set cpyStartCell = Range("C3")
Application.ScreenUpdating = False
OpenFile = Application.GetOpenFilename(Title:="Select a file to import data", filefilter:="Excel Files (*.xls*),*xls*")
If OpenFile <> False Then
Set ImportBook = Application.Workbooks.Open(OpenFile)
cpyLastRow = ImportBook.cpySheet.Cells(3, 1).End(xlDown).Row
'cpyLastColumn = cpyStartCell.Column
ImportBook.cpySheet.Range("C3", cpySheet.Cells(cpyLastRow, 3)).Copy
ThisWorkbook.ActiveSheet.Range("C3").PasteSpecial xlPasteValues
ImportBook.Close False
End If
Application.ScreenUpdating = True
End Sub
You get an error due to mixing import workbook property and active worbook sheet reference. Try to use method 1 or method 2. Be sure to specify actual sheet name in the import workbook.
'get reference to sheet "ABF - DAO" in active workbook
Set cpySheet = Sheets("ABF - DAO")
...
'error: mix workbook property and sheet reference
cpyLastRow = ImportBook.cpySheet.Cells(3, 1).End(xlDown).Row
'method 1: get reference to sheet in import workbook
Set cpySheet = ImportBook.Sheets("ABF - DAO")
cpyLastRow = cpySheet.Cells(3, 1).End(xlDown).Row
'method 2: get last row without sheet reference
cpyLastRow = ImportBook.Sheets("ABF - DAO")
Copy Column Range From Closed Workbook
Option Explicit
Private Sub CommandButton2_Click()
Const ProcName As String = "CommandButton2_Click"
On Error GoTo clearError
Const sTitle As String = "Select a file to import data"
Const sFilter As String = "Excel Files (*.xls*),*xls*"
Const sName As String = "DAO"
Const sFirst As String = "C3"
Const dFirst As String = "C3"
Dim dSuccess As Boolean
' Source
' Path
Dim sPath As Variant
sPath = Application.GetOpenFilename(Title:=sTitle, FileFilter:=sFilter)
If sPath = False Then
MsgBox "You canceled.", vbExclamation, "Canceled"
GoTo ProcExit
End With
Application.ScreenUpdating = False
' Worksheet
Dim swb As Workbook: Set swb = Workbooks.Open(sPath)
On Error Resume Next
Dim sws As Worksheet: Set sws = swb.Worksheets(sName)
On Error GoTo 0
If sws Is Nothing Then
CloseWithoutSaving swb
MsgBox "The worksheet '" & sName & "' does not exist.", _
vbCritical, "No Worksheet"
GoTo ProcExit
End If
' Range
Dim fCell As Range: Set fCell = sws.Range(sFirst)
With fCell
Dim lCell As Range
Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If lCell Is Nothing Then
CloseWithoutSaving swb
MsgBox "No data.", vbCritical, "No Data"
GoTo ProcExit
End If
Dim srg As Range: Set srg = .Resize(lCell.Row - .Row + 1)
End With
' Destination
' Assuming that the button is on the Destination Worksheet.
Dim dCell As Range: Set dCell = Range(dFirst)
' Otherwise, you should do something like this:
'Set dCell = ThisWorkbook.Worksheets("DAO").Range(dFirst)
' Copy (by Assignment)
dCell.Resize(srg.Rows.Count).Value = srg.Value
CloseWithoutSaving swb
dSuccess = True
ProcExit:
If Not Application.ScreenUpdating Then
Application.ScreenUpdating = True
End If
If dSuccess Then
MsgBox "Data transferred.", vbInformation, "Success"
End If
Exit Sub
clearError:
Debug.Print "'" & ProcName & "': Unexpected Error!" & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Sub
Sub CloseWithoutSaving( _
ByVal wb As Workbook)
Application.DisplayAlerts = False
wb.Close False
Application.DisplayAlerts = True
End Sub
I have the following code designed to copy a worksheet to a new location.
Sub XLSSave()
Sheets("Group Import").Copy
Cells.Copy
Cells.PasteSpecial xlPasteValues
ActiveWorkbook.SaveAs Filename:=Sheets("Group Import").Range("B22")
ActiveWorkbook.Close False
End Sub
Cell K67 is a file Path along the lines of
"C\Folder1\Folder2\Folder3\YYYY\MM\DD"
"C:\Folder1\Folder2\Folder3\YYYY\MM\DD".
The path "C:" was set correctly, I made a typo on the question.
I had intended to just concatenate the address within cell B22 as it needs to be dynamic.
It is exporting the Excel file as gibberish.
Export Worksheet
Easy
Option Explicit
Sub XLSSaveEasy()
Application.ScreenUpdating = False
Dim sws As Worksheet: Set sws = ThisWorkbook.Worksheets("Group Import")
sws.Copy
Dim dws As Worksheet: Set dws = ActiveWorkbook.Worksheets(1)
dws.UsedRange.Value = dws.UsedRange.Value
Application.DisplayAlerts = False
dws.Parent.SaveAs sws.Range("B22").Value, xlOpenXMLWorkbook
Application.DisplayAlerts = True
dws.Parent.Close False
Application.ScreenUpdating = True
End Sub
Not So Easy
Sub XLSSave()
Const swsName As String = "Group Import"
Const swsFilePathCell As String = "B22"
Dim sws As Worksheet: Set sws = ThisWorkbook.Worksheets(swsName)
Dim FilePath As String: FilePath = sws.Range(swsFilePathCell).Value
Dim FolderPath As String
FolderPath = Left(FilePath, InStrRev(FilePath, "\") - 1)
If Dir(FolderPath, vbDirectory) <> "" Then
Application.ScreenUpdating = False
sws.Copy
Dim dws As Worksheet: Set dws = ActiveWorkbook.Worksheets(1)
dws.UsedRange.Value = dws.UsedRange.Value
Application.DisplayAlerts = False
dws.Parent.SaveAs FilePath, xlOpenXMLWorkbook
Application.DisplayAlerts = True
dws.Parent.Close False
Application.ScreenUpdating = True
MsgBox "Backup of worksheet '" & swsName & "' created as '" _
& FilePath & "'.", vbInformation, "Success"
Else
MsgBox "The Folder '" & FolderPath & "' does not exist.", _
vbCritical, "Fail"
End If
End Sub
First: for disc C path must start from "C:\", in your case:
"C:\Folder1\Folder2\Folder3\YYYY\MM\DD"
Second: you must save file to already existing folder, for your case you must split path by "\" and check existence of all subfolders.
I was using below code to get the multiple CSV files into single sheet.
code is working fine but the issue is that, it should not copy the headers of each file, because each file header is same.
Code should copy the first file header not all files.
One more thing that i do not want first column to copy all sheets name i have tried to remove that filed but code does not work.
Can i get any help.
thanks
Sub CSV()
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder [Kutools for Excel]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = ThisWorkbook.ActiveSheet
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\" & "*.csv")
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
Columns(1).Insert xlShiftToRight
Columns(1).SpecialCells(xlBlanks).Value = ActiveSheet.Name
ActiveSheet.UsedRange.Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
xWb.Close False
xFile = Dir
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "no files csv", , "Kutools for Excel"
End Sub
EDIT: I did two attempts, first one untested, and did it on my phone:
Sub CSV()
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder [Kutools for Excel]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = ThisWorkbook.ActiveSheet
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\" & "*.csv")
Dim counter as Long
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
Dim sourceRange as Range
Set sourceRange = xWb.Worksheets(1).UsedRange
If counter = 0 then
sourceRange.Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
else
sourceRange.Offset(1, 0).Resize(sourceRange.Rows.Count - 1, sourceRange.Columns.Count).Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
End If
xWb.Close False
xFile = Dir
counter = counter + 1
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "no files csv", , "Kutools for Excel"
End Sub
Second attempt from my computer, I refactored the code handled first file case, skipped the clipboard and use proper procedure and variable names.
Public Sub ImportAndAppendCSVFromFolder()
' Set basic error handling
On Error GoTo CleanFail
' Turn off stuff
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
' Prepare and display file dialog to user
Dim customFileDialog As FileDialog
Set customFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
customFileDialog.AllowMultiSelect = False
customFileDialog.Title = "Select a folder"
' Get folder path from file dialog
If customFileDialog.Show = -1 Then
Dim folderPath As String
folderPath = customFileDialog.SelectedItems(1)
End If
' Exit if nothing was selected
If folderPath = vbNullString Then Exit Sub
' Set reference to active sheet (could be replaced to a specific sheet name with this: ThisWorkbook.Worksheets("SheetName") )
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.ActiveSheet
' Get files in directory ending with specific extension
Dim sourceFile As String
sourceFile = Dir(folderPath & "\" & "*.csv")
' Loop through files
Do While sourceFile <> ""
' Open file
Dim sourceWorkbook As Workbook
Set sourceWorkbook = Workbooks.Open(folderPath & "\" & sourceFile)
' Set reference to sheet in file (as it's a csv file, it only has one worksheet)
Dim sourceSheet As Worksheet
Set sourceSheet = sourceWorkbook.Worksheets(1)
' Depending if it's the first file, include headers or not
Dim counter As Long
If counter = 0 Then
' Set reference to used range in source file
Dim sourceRange As Range
Set sourceRange = sourceSheet.UsedRange
' Calc offset if it's first file
Dim rowOffset As Long
rowOffset = 0
Else
' Don't include headers in range
Set sourceRange = sourceSheet.UsedRange.Offset(1, 0).Resize(sourceSheet.UsedRange.Rows.Count - 1, sourceSheet.UsedRange.Columns.Count)
' Calc offset if it's not first file
rowOffset = 1
End If
' Perform copy (as this comes from a csv file, we can skip the clipboard
targetSheet.Range("A" & targetSheet.Rows.Count).End(xlUp).Resize(sourceRange.Rows.Count, sourceRange.Columns.Count).Offset(rowOffset).Value2 = sourceRange.Value2
' Close csv file
sourceWorkbook.Close False
' Get reference to next file
sourceFile = Dir
counter = counter + 1
Loop
CleanExit:
' Turn on stuff again
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Exit Sub
CleanFail:
MsgBox "An error occurred:" & Err.Description
GoTo CleanExit
End Sub