Hello folks,
I have a code and recorded macro. Could you please help me to merge the codes into one to be able to work with different range of data set?
Code #1: Combine files in a folder into a workbook
Sub MergeFiles()
Dim x As Integer
Const strDir = "C:\Mydoc\"
Dim ThisWB As Workbook
Dim wb As Workbook
Dim ws As Worksheet
Dim strWS As String
Dim sFileName As String
Set ThisWB = ActiveWorkbook
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = strDir
.Filters.Clear
.Filters.Add "CSV Files", "*.csv"
.Application.DisplayAlerts = False
If .Show Then
For x = 1 To .SelectedItems.Count
Set wb = Workbooks.Open(.SelectedItems(x))
sFileName = .SelectedItems(x)
Set ws = ThisWB.Worksheets.Add(before:=ThisWB.Worksheets(1))
ws.Name = ActiveSheet.Name
wb.Sheets(1).UsedRange.Copy ws.Range("A1")
wb.Close False
Next x
Else
MsgBox "There were no files found."
End If
End With
End Sub
Code #2: A recorded macro to convert 5 columns worksheet to 3 columns (Combining YMD columns into "Date" column)
The problem here is, I have to run the code for each worksheet separately, and I don't know how to do it for a workbook since the data range is not fixed.
I couldn't use the "Range("A" & Rows.Count).End(xlUp).Row" function correctly.
'2nd code for each sheet! How to do it for all sheets in a workbook?
Sub Macro5to3col()
'A recorded macro
'ColA = ID, ColB:D = Year,Month,Day & ColE = Value
'The goal is: Deleting ID, and combining YMD cols into "Date" column
Columns("A:A").Select
Selection.Delete Shift:=xlToLeft 'delete column A
Columns("D:D").Select 'insert two columns
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("D1").Select
ActiveCell.FormulaR1C1 = "Datetemp" 'a temporary Date column to avoid #REF! error
Range("D2").Select
ActiveCell.FormulaR1C1 = "=DATE(RC[-3],RC[-2],RC[-1])" '=Date(Y,M,D) function
Selection.AutoFill Destination:=Range("D2:D23012") 'The range is not fixed
Range("D2:D23012").Select
Selection.Copy
Range("E2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False 'Copy "Datetemp" column & paste as value in next column
Application.CutCopyMode = False
Selection.NumberFormat = "d/m/yyyy"
Range("E1").Select
ActiveCell.FormulaR1C1 = "Date"
Columns("A:D").Select 'delete YMD & Datetemp columns
Selection.Delete Shift:=xlToLeft
End Sub
Bookmarks