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
Related
I'm trying to loop through files in a folder with following path "C:\Users\Ouen\Downloads\Test" and paste each output into a new specific sheet in a MASTER workbook.
For example, the below are all the same worksbooks that each have a specific worksheet called "Annual" with different outputs:
Asset1
Asset2
Asset3
Etc
I would like to copy the whole Annual worksheet from each of the workbooks above and paste into a MASTER workbook, while being able to rename them to the following:
Asset1 - Annual
Asset2 - Annual
Asset3 - Annual
Etc
I have had some luck in copying and pasting from each workbook into the master but I'm unable to to paste each output into a new worksheet within the master and rename. Any ideas?
Sub Assets2Master()
Dim xRg As Range
Dim xSelItem As Variant
Dim xFileDlg As FileDialog
Dim xFileName, xSheetName, xRgStr As String
Dim xBook, xWorkBook As Workbook
Dim xSheet As Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
xSheetName = "Annual"
xRgStr = "B1:GI100"
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
With xFileDlg
If .Show = -1 Then
xSelItem = .SelectedItems.Item(1)
Set xWorkBook = ThisWorkbook
Set xSheet = xWorkBook.Sheets("MASTER")
If xSheet Is Nothing Then
xWorkBook.Sheets.Add(after:=xWorkBook.Worksheets(xWorkBook.Worksheets.Count)).Name = "MASTER"
Set xSheet = xWorkBook.Sheets("MASTER")
End If
xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
If xFileName = "" Then Exit Sub
Do Until xFileName = ""
Set xBook = Workbooks.Open(xSelItem & "\" & xFileName)
Set xRg = xBook.Worksheets(xSheetName).Range(xRgStr)
xRg.Copy xSheet.Range("A65536").End(xlUp).Offset(1, 0)
xFileName = Dir()
xBook.Close
Loop
End If
End With
et xRg = xSheet.UsedRange
xRg.ClearFormats
xRg.UseStandardHeight = True
xRg.UseStandardWidth = True
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Copy to the end
This code will copy, if it exists, the Annual worksheet from each workbook in the folder you select via the dialog.
They will be copied to the workbook the code is in and the copied sheets will be renamed with the name of the workbook they came from appended with - Annual.
The copied sheets will be copied after the last sheet in the MASTER workbook.
Sub Assets2Master()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim dlg As Object
Dim strFileName As String
Dim strFolder As String
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Set dlg = Application.FileDialog(msoFileDialogFolderPicker)
With dlg
If .Show = -1 Then
strFolder = .SelectedItems.Item(1)
End If
End With
Set wbDst = ThisWorkbook
strFileName = Dir(strFolder & "\*.xlsx", vbNormal)
If strFileName = "" Then Exit Sub
Do Until strFileName = ""
If strFileName <> wbDst.Name Then
Set wbSrc = Workbooks.Open(strFolder & "\" & strFileName)
' check if 'Annual' sheet exists, and if it does copy it to master workbook
If IfSheetExists("Annual", wbSrc) Then
Set wsSrc = wbSrc.Sheets("Annual")
With wbDst
wsSrc.Copy After:=.Sheets(.Sheets.Count)
.Sheets(.Sheets.Count).Name = Left(strFileName, Len(strFileName) - 5) & " - Annual"
End With
End If
wbSrc.Close SaveChanges:=False
End If
strFileName = Dir()
Loop
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Function IfSheetExists(strName As String, Optional wb As Workbook) As Boolean
' checks for the existence of a worksheet named strName in the, optional, workbook wb
' if wb not stated checks in the active workbook
Dim ws As Worksheet
If wb Is Nothing Then
Set wb = ActiveWorkbook
End If
For Each ws In wb.Sheets
If ws.Name = strName Then
IfSheetExists = True
Exit For
End If
Next ws
End Function
Copy after specific sheet
This code is basically identical to the previous code but the workheets will be copied after a specific worksheet in the MASTER workbook.
Option Explicit
Sub Assets2Master()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim dlg As Object
Dim strFileName As String
Dim strFolder As String
Dim lngDstIndex As Long
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Set dlg = Application.FileDialog(msoFileDialogFolderPicker)
With dlg
If .Show = -1 Then
strFolder = .SelectedItems.Item(1)
End If
End With
Set wbDst = ThisWorkbook
' change Specific Tab to the name ypu want the sheets to be copied after
lngDstIndex = wbDst.Sheets("Specific Tab").Index
strFileName = Dir(strFolder & "\*.xlsx", vbNormal)
If strFileName = "" Then Exit Sub
Do Until strFileName = ""
If strFileName <> wbDst.Name Then
Set wbSrc = Workbooks.Open(strFolder & "\" & strFileName)
' check if 'Annual' sheet exists, and if it does copy it to master workbook
If IfSheetExists("Annual", wbSrc) Then
Set wsSrc = wbSrc.Sheets("Annual")
With wbDst
' copy sheet to MASTER workbook
wsSrc.Copy After:=.Sheets(.Sheets.Count)
' rename sheet and move it after specified sheet
With .Sheets(.Sheets.Count)
.Name = Left(strFileName, Len(strFileName) - 5) & " - Annual"
.Move After:=wbDst.Sheets(lngDstIndex)
lngDstIndex = lngDstIndex + 1
End With
End With
End If
wbSrc.Close SaveChanges:=False
End If
strFileName = Dir()
Loop
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Function IfSheetExists(strName As String, Optional wb As Workbook) As Boolean
' checks for the existence of a worksheet named strName in the, optional, workbook wb
' if wb not stated checks in the active workbook
Dim ws As Worksheet
If wb Is Nothing Then
Set wb = ActiveWorkbook
End If
For Each ws In wb.Sheets
If ws.Name = strName Then
IfSheetExists = True
Exit For
End If
Next ws
End Function
Try this. The Master wb should be placed in a different folder than the one you store the Asset Files:
Sub Assets2Master()
Dim xRg As Range
Dim xSelItem As Variant
Dim xFileDlg As FileDialog
Dim xFileName, xSheetName, xRgStr As String
Dim xBook, xWorkBook As Workbook
Dim xSheet As Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
xSheetName = "Annual"
xRgStr = "B1:GI100"
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
With xFileDlg
If .Show = -1 Then
xSelItem = .SelectedItems.item(1)
Set xWorkBook = ActiveWorkbook
Set xSheet = xWorkBook.Sheets("MASTER")
If xSheet Is Nothing Then
xWorkBook.Sheets.Add(After:=xWorkBook.Worksheets(xWorkBook.Worksheets.count)).Name = "MASTER"
Set xSheet = xWorkBook.Sheets("MASTER")
End If
xFileName = Dir(xSelItem & "\*.xlsx", vbNormal)
If xFileName = "" Then Exit Sub
Do Until xFileName = ""
Set xBook = Workbooks.Open(xSelItem & "\" & xFileName)
Set xRg = xBook.Worksheets(xSheetName).Range(xRgStr)
xRg.Copy xSheet.Range("A65536").End(xlUp).Offset(1, 0)
xFileName = Dir()
xBook.Close
xBook.Name = xBook.Name & " - Annual"
Loop
End If
End With
Set xRg = xSheet.UsedRange
xRg.ClearFormats
xRg.UseStandardHeight = True
xRg.UseStandardWidth = True
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Stack Ranges
This is about what I thought your code was supposed to do. What you asked for is kind of illustrated with the commented block of code in the Do...Loop. By modifying the code in the Do...Loop, there are many possibilities of what you could achieve.
Option Explicit
Sub StackRanges()
' Source
Const sName As String = "Sheet1" ' "Annual"
Const sAddress As String = "B1:GI100"
' Destination
Const dName As String = "MASTER"
Const dCol As String = "A"
Application.ScreenUpdating = False
' Open the dialog to pick a folder.
Dim xFileDlg As FileDialog
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
Dim sFolderPath As Variant
With xFileDlg
.InitialFileName = ThisWorkbook.Path
If .Show = True Then
sFolderPath = .SelectedItems.Item(1)
Else
MsgBox "Canceled.", vbExclamation, "Assets2Master"
Exit Sub
End If
End With
' Write the name of the first file to the Source File Name variable.
Dim sfName As String: sfName = Dir(sFolderPath & "\*.xlsx")
' Validate first Source File Name.
If Len(sfName) = 0 Then Exit Sub ' no files found
' Create a reference to the Destination Workbook.
Dim dwb As Workbook: Set dwb = ThisWorkbook
' Write the name of the Destination Workbook
' to the Destination File Name variable.
Dim dfName As String: dfName = dwb.Name
' Attempt to create a reference to the Destination Worksheet.
Dim dws As Worksheet
On Error Resume Next
Set dws = dwb.Worksheets(dName)
On Error GoTo 0
' If the attempt was unsuccessful, add a new worksheet and do it now.
If dws Is Nothing Then
dwb.Worksheets.Add(After:=dwb.Sheets(dwb.Sheets.Count)).Name = dName
Set dws = dwb.Worksheets(dName)
' Maybe add some headers... to the Destination Worksheet.
End If
' Create a reference to the (first) Destination Range.
Dim drg As Range: Set drg = dws.Range(sAddress)
Dim rCount As Long: rCount = drg.Rows.Count
Dim cCount As Long: cCount = drg.Columns.Count
Set drg = dws.Cells(dws.Rows.Count, dCol).End(xlUp) _
.Offset(1, 0).Resize(rCount, cCount)
' Declare additional variables for the following 'Do Loop'.
Dim swb As Workbook
Dim sws As Worksheet
Dim srg As Range
' Loop through the files in the folder...
Do Until Len(sfName) = 0
' Check if the Source File Name is different
' than the Destination File Name.
If StrComp(sfName, dfName, vbTextCompare) <> 0 Then
' Open and create a reference to the Source Workbook.
Set swb = Workbooks.Open(sFolderPath & "\" & sfName)
' Attempt to create a reference to the Source Worksheet.
Set sws = Nothing
On Error Resume Next
Set sws = swb.Worksheets(sName)
On Error GoTo 0
' Stack Ranges
' If the attempt was successful...
If Not sws Is Nothing Then
' Create a reference to the Source Range.
Set srg = sws.Range(sAddress)
' Copy the values from the Source to the Destination Range
' by assignment.
drg.Value = srg.Value
' Create a reference to the (next) Destination Range.
Set drg = drg.Offset(rCount)
End If
' ' Copy Worksheets (instead)
'
' ' If the attempt was successful...
' If Not sws Is Nothing Then
' sws.Copy After:=dwb.Sheets(dwb.Sheets.Count)
' ' Caution: Has to be less than 32 characters!
' ActiveSheet.Name = Left(sfName, Len(sfName) - 5) & " - " & sName
' End If
' Close the Source Workbook.
swb.Close SaveChanges:=False
End If
' Write the name of the next file to the Source File Name variable.
sfName = Dir
Loop
Application.ScreenUpdating = True
' Inform the user.
MsgBox "Data copied.", vbInformation, "Assets2Master"
End Sub
I run a machine which puts out multiple text files which I plot, I have a VBA script which can import all of the files I want to plot from a folder and puts them on their own sheet. I was wondering if there was a way in which I could automatically have them plotted when they are imported as well? I need a separate graph for each pair of tests. That is I have "Test A-1" and "Test A-2" which are plotted against each other, "Test B-1" and "Test B-2" on a new graph etc. Sorry if this is confusing, I am still pretty new to VBA and would love a tool like this to make my life a bit easier. I have included my code which does all the importing below. Each text file (which is just data for a x-y scatter plot) is then given its own sheet, with the data in columns A and B. Apologies in advance for the terrible formatting, I didn't write it!
Sub ImportTextToExcel()
'UpdatebyExtendoffice20180911
Dim xWb As Workbook
Dim xToBook As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xFiles As New Collection
Dim I As Long
Dim xIntRow As Long
Dim xFNum, xFArr As Long
Dim xStrValue As String
Dim xRg As Range
Dim xArr
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
xFile = Dir(xStrPath & "*.txt")
If xFile = "" Then
MsgBox "No files found", vbInformation
Exit Sub
End If
Do While xFile <> ""
xFiles.Add xFile, xFile
xFile = Dir()
Loop
Set xToBook = ThisWorkbook
On Error Resume Next
Application.ScreenUpdating = False
If xFiles.Count > 0 Then
For I = 1 To xFiles.Count
Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
ActiveSheet.Name = xWb.Name
xWb.Close False
xIntRow = ActiveCell.CurrentRegion.Rows.Count
For xFNum = 1 To xIntRow
Set xRg = ActiveSheet.Range("A" & xFNum)
xArr = Split(xRg.Text, " ")
If UBound(xArr) > 0 Then
For xFArr = 0 To UBound(xArr)
If xArr(xFArr) <> "" Then
xRg.Value = xArr(xFArr)
Set xRg = xRg.Offset(ColumnOffset:=1)
End If
Next
End If
Next
Next
End If
Application.ScreenUpdating = True
End Sub
Option Explicit
Sub ImportTextToExcel()
'UpdatebyExtendoffice20180911
Dim xWb As Workbook, xToBook As Workbook, ws As Worksheet
Dim xFile As String, xStrPath As String, xStrValue As String
Dim xRg As Range, cht As Chart
Dim xFiles As New Collection
Dim i As Long
' choose folder
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "Select a folder"
If .Show = -1 Then
xStrPath = .SelectedItems(1)
End If
End With
If xStrPath = "" Then
Exit Sub
ElseIf Right(xStrPath, 1) <> "\" Then
xStrPath = xStrPath & "\"
End If
' build collection of text files
xFile = Dir(xStrPath & "*.txt")
Do While xFile <> ""
xFiles.Add xFile, xFile
xFile = Dir()
Loop
If xFiles.Count = 0 Then
MsgBox "No files found", vbCritical
Exit Sub
End If
' import data
Set xToBook = ThisWorkbook
Application.ScreenUpdating = False
For i = 1 To xFiles.Count
' import data into new sheet
Set xWb = Workbooks.Open(xStrPath & xFiles.Item(i))
xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
Set ws = ActiveSheet
ws.Name = xWb.Name
xWb.Close False
' split on space
Set xRg = ws.Range("A1")
xRg.CurrentRegion.TextToColumns Destination:=xRg.Cells(1, 1), _
DataType:=xlDelimited, _
ConsecutiveDelimiter:=True, _
Space:=True, FieldInfo:=Array(Array(1, 1), Array(2, 1))
' create chart
Set cht = ws.Shapes.AddChart.Chart
With cht
.ChartType = xlXYScatter
.SetSourceData Source:=xRg.CurrentRegion
End With
Next
Application.ScreenUpdating = True
MsgBox xFiles.Count & " files imported", vbInformation
End Sub
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
I have multiple CSV in one directory, I need to select specific files instead of the entire directory and I want to be able to select the column that I want (X) and import this to a single worksheet!
I have already made the code above but I'm fighting to add a input box that give the capability do select the column that I want to extract from each CSV.
Moreover, whenever I import the CSV there are not sorted correctly. I found out that I need to apply this formula ""=LEFT(F1;1)&TEXT(SUBSTITUTE(F1;LEFT(F1;1);"";"00") " ", but any idea how to apply in code in order to rename the .csv files.
Sub ImportCSVsWithReferenceI()
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Dim xCount As Long
Dim Newname As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = ThisWorkbook.ActiveSheet.Add
Newname = InputBox("Name for new worksheet?")
If Newname <> "" Then
Sheets.Add Type:=xlWorksheet
ActiveSheet.Name = Newname
End If
Set xSht = ThisWorkbook.ActiveSheet
If MsgBox("Clear the existing sheet before importing?", vbYesNo, "Kutools for Excel") = vbYes Then
xSht.UsedRange.Clear
xCount = 1
Else
xCount = xSht.Cells(3, Columns.Count).End(xlToLeft).Column + 1
End If
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\" & "*.csv")
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
Rows(1).Insert xlShiftDown
Range("A1") = ActiveSheet.Name
ActiveSheet.UsedRange.Copy xSht.Cells(1, xCount)
xWb.Close False
xFile = Dir
xCount = xSht.Cells(3, Columns.Count).End(xlToLeft).Column + 1
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "error"
End Sub
Data example (some times I want to extract the columns A or B or C or .... :
Example of a result:
I'm have about 100 .xls files under one folder and I have a Macro script to loop through each one to do some data processing. The objective is to split each workbook into three with name N1, N2, N3 respectively. So far my SplitData Macro worked fine but I have issue with extracted workbooks.
I want to merge newly extracted three workbooks to already existed ones instead of getting alerts like "File N1 already exists." every time. I changed Application.DisplayAlerts = false because of my previous question's suggested answer but now I got a new error:
After the alert is disabled, my first two extracted workbook keeps updating same result from the first workbook that I started extraction while the third one trapped in a loop, adding same result from the starting workbook. I assume there's something wrong with my loop but cannot find it, can anyone help me check please?
Thanks a lot!
This is my code to loop through folder:
Sub OpenFiles()
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
On Error Resume Next
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
xFile = Dir(xStrPath & "\*.xls")
Do While xFile <> ""
Call SplitData
Loop
End Sub
This is SplitData Macro:
Sub SplitData()
' 1. Fill every cells in merged columns for future steps
Dim cell As Range, joinedCells As Range
For Each cell In Range("E4:I60")
If cell.MergeCells Then
Set joinedCells = cell.MergeArea
cell.MergeCells = False
joinedCells.Value = cell.Value
End If
Next
' 2. Split original sheet into three based on one col value
' loop through selected column to check if has different values
Const NameCol = "B"
Const HeaderRow = 3
Const FirstRow = 4
Dim SrcSheet As Worksheet
Dim TrgSheet As Worksheet
Dim SrcRow As Long
Dim LastRow As Long
Dim TrgRow As Long
Dim Student As String
Application.ScreenUpdating = False
Set SrcSheet = ActiveSheet
LastRow = SrcSheet.Cells(SrcSheet.Rows.Count, NameCol).End(xlUp).Row
For SrcRow = FirstRow To LastRow
Student = SrcSheet.Cells(SrcRow, NameCol).Value
Set TrgSheet = Nothing
On Error Resume Next
Set TrgSheet = Worksheets(Student)
On Error GoTo 0
If TrgSheet Is Nothing Then
Set TrgSheet = Worksheets.Add(After:=Worksheets(Worksheets.Count))
TrgSheet.Name = Student
SrcSheet.Rows(HeaderRow).Copy Destination:=TrgSheet.Rows(HeaderRow)
End If
TrgRow = TrgSheet.Cells(TrgSheet.Rows.Count, NameCol).End(xlUp).Row + 1
SrcSheet.Rows(SrcRow).Copy Destination:=TrgSheet.Rows(TrgRow)
Next SrcRow
Application.ScreenUpdating = True
' 3. Extract three new worksheets into three workbooks
Dim Pointer As Long
Set MainWorkBook = ActiveWorkbook
Range("E4").Value = MainWorkBook.Sheets.Count
Application.ScreenUpdating = False 'enhance the performance
For Pointer = 2 To MainWorkBook.Sheets.Count
Set NewWorkbook = Workbooks.Add
MainWorkBook.Sheets(Pointer).Copy After:=NewWorkbook.Sheets(1)
Application.DisplayAlerts = False
NewWorkbook.Sheets(1).Delete
Application.DisplayAlerts = False
With NewWorkbook
.SaveAs Filename:="D:\***\Inventory\" & MainWorkBook.Sheets(Pointer).Name & ".xls"
End With
NewWorkbook.Close SaveChanges:=True
Next Pointer
Application.ScreenUpdating = True
End Sub
It seems to have to open and close the file.
Sub OpenFiles()
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
On Error Resume Next
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a folder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
xFile = Dir(xStrPath & "\*.xls")
Dim Wb As Workbook
Do While xFile <> ""
Set Wb = Workbooks.Open(Filename:=xStrPath & "\" & xFile) '<~~ open file
Call SplitData
Wb.Close (0) '<~~ close file
xFile = Dir '<~~ re dir
Loop
End Sub
You need to add xFile = Dir in your loop to cycle through the files.
...
xFile = Dir(xStrPath & "\*.xls")
Do While xFile <> ""
Call SplitData
xFile = Dir
Loop
...
It's unclear on how xFile gets passed to SplitData. Shouldn't SplitData have an argument that receives xFile?