barcode_11
New Member
- Joined
- Feb 28, 2018
- Messages
- 12
Hi, I have a code that I am trying to improve and adopt, however, struggling to merge the values horizontally. It copies perfectly however pastes values on top of the earlier values pasted. Any help to improve the code will be greatly appreciated. Please see the code below.
Code:
Sub MergeCSVFiles()
Dim wb As Workbook
Dim wbCSV As Workbook
Dim myPath As String
Dim myFile As Variant
Dim fileType As String
Dim i As Integer
Dim ws As Worksheet
Dim Destws As Worksheet
Dim CopyRng As Range
Dim lastcol As Long
Dim lastrow As Long
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Source Folder"
.AllowMultiSelect = False
.Show
myPath = .SelectedItems(1) & "\"
End With
fileType = "*.csv*"
myFile = Dir(myPath & fileType)
Workbooks.Add
ActiveWorkbook.SaveAs Filename:= _
myPath & "Total Results.xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Set wb = Workbooks.Open(myPath & "Total Results.xlsm")
Do While myFile <> ""
Worksheets.Add(Before:=Worksheets("Sheet1")).Name = "Image " & i + 1
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & myPath & myFile _
, Destination:=ActiveSheet.Range("$A$1"))
.Name = myFile
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
i = i + 1
myFile = Dir
Loop
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("MergedSheet").Delete
On Error GoTo 0
Application.DisplayAlerts = True
Set Destws = ActiveWorkbook.Worksheets.Add
Destws.Name = "MergedSheet"
Sheets(1).Activate
Rows("1:2").Select
Selection.Copy
Destws.Activate
Rows("1:2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
For Each ws In ActiveWorkbook.Worksheets
If ws.Name <> Destws.Name Then
ws.Activate
With ws
lastrow = 2 + Cells(Rows.Count, "E").End(xlUp).Row
Set CopyRng = ws.Range(ws.Rows("3"), ws.Rows(lastrow))
CopyRng.Copy
End With
Destws.Activate
With Destws
lastcol = Cells("4", Columns.Count).End(xlToLeft).Columns
With Destws.Cells("4", lastcol + 1)
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
End With
End If
Next
MsgBox "Result Merge Complete"
End Sub