VBA to import multiple CSV files into multiple sheets in excel - vba

I am working to make an automated template that imports multiple csv files into multiple sheets in an excel template that I have created.
So far I have one sheet in the template that has a table named Results and a column named Login ID. I wrote the following script to automatically create sheets and name them. My table data starts on row 7.
Sub Prepare_Report()
Dim WS As Worksheet
' Go to the results page
Sheets("Results Page").Select
' Create all additional sheets from Login ID field in the results table
Dim N As Long, I As Long
N = Range("Results[Login ID]").Rows.Count + 6
For I = 7 To N
aName = Worksheets("Results Page").Range("C" & I).Value
Set WS = Sheets.Add(After:=Sheets(Worksheets.Count))
WS.Name = aName
Next I
Each CSV file I have to import is named after one of the Login ID's as well, and they will be located in the same folder as the template I am creating.
the CSV files will need a slight modification to separate the date and time from the first column.
' Columns("A:A").Select
' Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
' Columns("B:B").Select
' Selection.Cut Destination:=Columns("A:A")
' Columns("A:A").Select
' Selection.TextToColumns Destination:=Range("A1"), DataType:=xlFixedWidth, _
' FieldInfo:=Array(Array(0, 1), Array(10, 1)), TrailingMinusNumbers:=True
' Columns("A:A").Select
' Selection.NumberFormat = "mm/dd/yy;#"
' Columns("B:B").Select
' Columns("B:B").EntireColumn.AutoFit
'
Any ideas if I am on the right track or how to best solve my CSV import woes would be much appreciated.

This will do what you want!
Sub CombineTextFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="CSV Files (*.csv), *.csv", _
MultiSelect:=True, Title:="CSV Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
x = x + 1
While x <= UBound(FilesToOpen)
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
With wkbAll
wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
End With
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub

Related

.txt to separate worksheets

I'm trying to use the following code to import multiple .txt into separate separate sheets in a workbook. In all of the worksheets it fails to space delimit the last row and from worksheet 2 onward it also fails to copy the first line of the .txt file. All the txt. files are the exactly the same format. Any help appreciated.
Sub CombineTextFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, Semicolon:=False, _
Comma:=False, Space:=True, Other:=False, OtherChar:="|"
Dim lastrowA As Long
Dim lastrowB As Long
Dim sheetname As String
With ActiveSheet
lastrowA = .Cells(.Rows.Count, "A").End(xlUp).Row
lastrowB = .Cells(.Rows.Count, "B").End(xlUp).Row
sheetname = ActiveSheet.Name
Range("a1").EntireColumn.Insert
Range("a1").Value = sheetname
Range("a2" & ":a" & lastrowB).Value = Range("a1")
Range("a1").EntireRow.Insert
End With
x = x + 1
While x <= UBound(FilesToOpen)
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
With wkbAll
wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, Semicolon:=False, _
Comma:=False, Space:=True, Other:=False
End With
With ActiveSheet
lastrowA = .Cells(.Rows.Count, "A").End(xlUp).Row
lastrowB = .Cells(.Rows.Count, "B").End(xlUp).Row
sheetname = ActiveSheet.Name
Range("a1").Value = sheetname
Range("a2" & ":a" & lastrowB).Value = Range("a1")
Range("a1").EntireRow.Insert
End With
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
If you make a minimal, complete, and verifiable example, you would probably find the mistake yourself. However, by your description for the first row, I guess the problem is here:
With ActiveSheet
lastrowA = .Cells(.Rows.Count, "A").End(xlUp).Row
lastrowB = .Cells(.Rows.Count, "B").End(xlUp).Row
sheetname = ActiveSheet.Name
Range("a1").EntireColumn.Insert
Range("a1").Value = sheetname
Range("a2" & ":a" & lastrowB).Value = Range("a1")
Range("a1").EntireRow.Insert
End With
You need to declare the ranges like this:
With ActiveSheet
lastrowA = .Cells(.Rows.Count, "A").End(xlUp).Row
lastrowB = .Cells(.Rows.Count, "B").End(xlUp).Row
sheetname = ActiveSheet.Name
.Range("a1").EntireColumn.Insert
.Range("a1").Value = sheetname
.Range("a2" & ":a" & lastrowB).Value = .Range("a1")
.Range("a1").EntireRow.Insert
End With
See the dots, they make the difference. If the code is located in a worksheet, then the ranges take the worksheet they are located to, as a Parent worksheet.

Excel VBA - text files to separate worksheets: Object variable or with block variable not set

This Code (Source) serves to take multiple text files, all in the same folder, and make a separate worksheet out of each one. It works for one file, but when it's time to execute on a second file, I get the error message in the title.
I believe all variables are set and I have tried setting variables in the loop, along with moving the incrementor around, and changing xTempWb.Sheets(1).Copy to xTempWb.Sheets(1).Add. I have also consulted a number of Stack Overflow questions and the MSDN documentation.
It jumps to the error handler at the line: xTempWb.Sheets(1).Copy
Sub CombineTextFiles()
'update by ExtendOffice 20151015
Dim xFilesToOpen As Variant
Dim I As Integer
Dim xWb As Workbook
Dim xTempWb As Workbook
Dim xDelimiter As String
Dim xScreen As Boolean
On Error GoTo ErrHandler
xScreen = Application.ScreenUpdating
Application.ScreenUpdating = False
xDelimiter = "|"
xFilesToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Kutools for Excel",, True)
If TypeName(xFilesToOpen) = "Boolean" Then
MsgBox "No files were selected", . "KuTools for Excel"
GoTo ExitHandler
End If
I = 1
Set xTembWb = Workbooks.Open(xFilesToOpen(I))
xTempWb.Sheets(1).Copy
Set xWb = Application.ActiveWorkbook
xTempWb.Close False
xWb.Worksheets(I).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType = xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, SemiColon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
Do While I < UBound(xFilesToOpen)
I = I + 1
Set xTembWb = Workbooks.Open(xFilestoOpen(I))
With xWb
xTempWb.Sheets(1).Move after:=.Sheets(.Sheets.Count)
.Worksheets(I).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=xDelimiter
End With
Loop
ExitHandler:
Application.ScreenUpdating = xScreen
Set xWb = Nothing
Set xTempWb = Nothing
Exit Sub
ErrHandler
MsgBox Err.Description, , "KuTools For Excel"
Resume ExitHandler
End Sub
End Sub
enter code here
There looks to be several issues with the code above and some unncessary lines. After Getting xFilesTopOpen adjust your code to below.
Please also notice there was a place where you misspelled xTempWb as xTembWB. Using Option Explicit above your code will help ensure all variables are named as needed.
Set xWB = ThisWorkbook
Dim wbCounter as Integer
For wbCounter = LBound(xFilesToOpen) to UBound(xFilesToOpen)
Set xTempWb = Workbooks.Open(xFilesToOpen(I))
xTembWb.Sheets(1).Copy xWB.Worksheets(xWB.Worksheets.Count)
Dim ws as Worksheet
Set ws = Activesheet
ws.Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType = xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, SemiColon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
xTempWb.Close False
Next
Use
Option Explicit
You have declared Dim xTempWb As Workbook
and you are setting your text files to Set xTembWb = Workbooks.Open(xFilesToOpen(I)) and then trying to use xTempWb once again.
That's the issue.

Close temporary workbook

I picked up this code from the web. It merges several Excel files to single file (each in separate sheets).
The files the DATA is imported from don't automatically close. This means that I need to manually close 8-10 files and "Do not Save" them, and that takes lots of time. What is the missing code?
Option Explicit
Sub CombineExcelFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Excel Files (*.*xl*), *.*xl*", _
MultiSelect:=True, Title:="Excel Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
x = x + 1
While x <= UBound(FilesToOpen)
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
With wkbAll
wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
End With
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
wkbTemp.Close False should close the workbook without saving it.
But another question is why do you process the first file outside the While loop? I see no reason for this. Therefore we can shorten that code to:
Option Explicit
Public Sub CombineExcelFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Excel Files (*.*xl*), *.*xl*", _
MultiSelect:=True, Title:="Excel Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Set wkbAll = ActiveWorkbook
While x <= UBound(FilesToOpen)
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
With wkbAll
wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
wkbTemp.Close False
.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
End With
x = x + 1
Wend
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
Some Important Notes
I recommend to avoid ActiveWorkbook if possible because it is not a defined workbook but any workbook that is active at just this moment. Also note that there is a difference between ActiveWorkbook and ThisWorkbook (which is a defined workbook. It is the workbook the code runs at this point).*
Another thing is that .Worksheets(x) can be, but not necessarily must be the actually moved worksheet. I would say because you move the new sheet after the last sheet you also need to access the last sheet here: .Worksheets(.Worksheets.Count).
Also there is a difference between using Sheets and Worksheets. The Sheets collection contains worksheets but also charts etc, but the Worksheets collection only contains worksheets. Therefore you should decide which one is correct, I recommend always to use Worksheets unless you really need Sheets.
And I see no need for setting the variables to nothing.
Set wkbAll = Nothing
Set wkbTemp = Nothing
If I'm not totally wrong then Excel does this automatically when the procedure ends.

Import Multiple text files into workbook where worksheet name matches text file name

Introduction: With continuation to my previous question, initially, my previous code (with the help from Stack exchange experts) works fine.
Problem: But next time when I import the files again (which I have to do monthly), it creates duplicate Sheets. So I would like to modify my project as follows.
On clicking "Import text files" button, the VBA code:
Check the existing Workbook for the sheet names matching the text file name. If existing, clear the contents of the sheet and copy the data into the sheet.
For example, If my text file names are like "Data_REQ1", "Data_REQ2" and so on until Data_REQ30, the code should check for sheets starting with Data_REQ1, if exists clear the contents, copy the data from text file Data_REQ1 into the sheet Data_REQ1 and so on for other sheets.
Pseudo code:
Check Sheets existence
If Sheet name exists Then
Clear contents
Copy the data from text file having sheet name=textfile name
Else
Create the Sheet and import the data into the sheet
Here is my full code
Sub copydata()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim sDelimiter As String
Dim ws As Worksheet
Dim lastCol As Integer
Dim lastRow As Integer
Dim TextFileName As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
'Open First text File then format the data with delimiter and copy the data
x = 1
With Workbooks.Open(filename:=FilesToOpen(x))
TextFileName = Sheets(1).Name
.Worksheets(1).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
lastCol = Sheets(TextFileName).Range("a1").End(xlToRight).Column
lastRow = Sheets(TextFileName).Cells(65536, lastCol).End(xlUp).Row
Selection.Copy
.Close False
'clear the contents of the sheets, copy the data into the sheet with same name as text file
With ThisWorkbook.Worksheets(TextFileName)
lastCol = Sheets(TextFileName).Range("a1").End(xlToRight).Column
lastRow = Sheets(TextFileName).Cells(65536, lastCol).End(xlUp).Row
Sheets(TextFileName).Range("a1", ActiveSheet.Cells(lastRow, lastCol)).Select
Selection.ClearContents
Sheets(TextFileName).Range("A1").PasteSpecial
End With
End With
'This loop is for other files , if the above code works for 1 file, I will change this code for other files
x = x + 1
While x <= UBound(FilesToOpen)
With Workbooks.Open(filename:=FilesToOpen(x))
.Worksheets(1).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
.Sheets(1).Move After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
End With
x = x + 1
Wend
Call fitWidth(ws)
wkbAll.Save
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
Sub fitWidth(ws As Worksheet)
For Each ws In Sheets
If LCase(ws.Name) Like "data_req*" Then
ws.Cells.EntireColumn.AutoFit
End If
Next
End Sub
Here is the code which I tried to change from previous version
Previous version:
With Workbooks.Open(filename:=FilesToOpen(x))
.Worksheets(1).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
.Sheets(1).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
.Close False
Present Version
x = 1
With Workbooks.Open(fileName:=FilesToOpen(x))
TextFileName = Sheets(1).Name
.Worksheets(1).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
lastCol = Sheets(TextFileName).Range("a1").End(xlToRight).Column
lastRow = Sheets(TextFileName).Cells(65536, lastCol).End(xlUp).Row
Selection.Copy
.Close False
'clear the contents of the sheets, copy the data into the sheet with same > name as text file
With ThisWorkbook.Worksheets(TextFileName)
lastCol = Sheets(TextFileName).Range("a1").End(xlToRight).Column
lastRow = Sheets(TextFileName).Cells(65536, lastCol).End(xlUp).Row
Sheets(TextFileName).Range("a1", ActiveSheet.Cells(lastRow, lastCol)).Select
Selection.ClearContents
Sheets(TextFileName).Range("A1").PasteSpecial
End With
My Request: With this change, I am able to clear contents, but not pasting the data. Any suggestions or any code better than this code will be appreciated.
Consider using QueryTables to import text files. No need to copy/paste across temp workbooks:
Sub ImportTXTFiles()
Dim fso As Object
Dim xlsheet As Worksheet
Dim qt As QueryTable
Dim txtfilesToOpen As Variant, txtfile As Variant
Application.ScreenUpdating = False
Set fso = CreateObject("Scripting.FileSystemObject")
txtfilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
For Each txtfile In txtfilesToOpen
' FINDS EXISTING WORKSHEET
For Each xlsheet In ThisWorkbook.Worksheets
If xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "") Then
xlsheet.Activate
GoTo ImportData
End If
Next xlsheet
' CREATES NEW WORKSHEET IF NOT FOUND
Set xlsheet = ThisWorkbook.Worksheets.Add( _
After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
xlsheet.Name = Replace(fso.GetFileName(txtfile), ".txt", "")
xlsheet.Activate
GoTo ImportData
ImportData:
' DELETE EXISTING DATA
ActiveSheet.Range("A:Z").EntireColumn.Delete xlShiftToLeft
' IMPORT DATA FROM TEXT FILE
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & txtfile, _
Destination:=ActiveSheet.Cells(1, 1))
.TextFileParseType = xlDelimited
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "|"
.Refresh BackgroundQuery:=False
End With
For Each qt In ActiveSheet.QueryTables
qt.Delete
Next qt
Next txtfile
Application.ScreenUpdating = True
MsgBox "Successfully imported text files!", vbInformation, "SUCCESSFUL IMPORT"
Set fso = Nothing
End Sub

import multiple text files to seperate sheets in the existing workbook

I have an excel file (2013) (eg test.xlsm). The excel file contains sheets with graphs and pivot tables which are refreshed monthly, based on text files. I need a VBA code which can import multiple text files from my local drive (which I import from a server) and append them at the end (sheets named similar to text file names) in this excel file. Every month, when I import text files, it has to replace this data sheets with new files.
Problem:
I have found a VBA code in this link! It works perfectly fine. But my problem is it imports the data into a newly opened Workbook instead of existing Workbook.
Solution
I modified the lines from
Set wkbAll = ActiveWorkbook
wkbTemp.Sheets(1).Copy
to
Set wkbAll = ThisWorkbook
wkbAll.Activate
wkbTemp.Sheets(1).Copy After:=Sheets(wkbAll.Sheets.Count)
but I get error 1004, no data selected to format the data with delimiter
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
Solution
I have found the some questions similar to mine (like this one), but none of them worked for me.
Please help me to solve this problem.
Here is my code with changes
Sub copydata()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
Set wkbAll = Application.ActiveWorkbook
x = 1
With Workbooks.Open(fileName:=FilesToOpen(x))
.Worksheets(1).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
.Sheets(1).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.count)
.Close False
End With
x = x + 1
While x <= UBound(FilesToOpen)
With Workbooks.Open(fileName:=FilesToOpen(x))
.Worksheets(1).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
.Sheets(1).Move After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.count)
End With
x = x + 1
Wend
wkbAll.Save
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
edited after OP's new request (see bottom of the answer)
change
wkbTemp.Sheets(1).Copy After:=Sheets(wkbAll.Sheets.Count)
to
wkbTemp.Sheets(1).Copy After:=wkbAll.Sheets(wkbAll.Sheets.Count)
thus you can also change the whole section:
Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
Set wkbAll = ThisWorkbook
wkbAll.Activate
wkbTemp.Sheets(1).Copy After:=Sheets(wkbAll.Sheets.Count)
wkbTemp.Close (False)
to
With Workbooks.Open(Filename:=FilesToOpen(x))
.Sheets(1).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.count)
.Close False
End With
and get rid of wkbTemp variable at all
should you need to copy data into an existing worksheet of the same workbook, then substitute
With Workbooks.Open(Filename:=FilesToOpen(x))
.Sheets(1).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.count)
.Close False
End With
with
With Worksheets("Data1") '<--| change "Data1" to your actual name of existing sheet where to paste data into
.UsedRange.ClearContents
Worksheets(1).UsedRange.Copy .Range("A1")
End With