VBA Copy and Paste Transpose data from Multiple columns - vba

I have multiple Timesheet workbooks set up which has Employee Name and multiple columns for different hour types (eg. Base Hours, Holiday Pay, Sick Pay). See image .
I need code to be able to copy for each employee the type of hours (heading) and the value into 4 columns.
eg.
Employee 1 Base Hours 37.50
Employee 1 Sick Hours 15.00
Employee 1 Group Leader 20.00
Employee 2 Base Hours 50.00
Employee 2 Holiday Pay 60.00
I have some code which copies the data to a template currently but stuck on how to copy it as above.
Sub Consolidate()
Application.EnableCancelKey = xlDisabled
Dim folderPath As String
Dim Filename As String
Dim wb As Workbook
Dim FName As String
Dim FPath As String
Dim NewBook As Workbook
folderPath = "C:\Users\preena.j\Documents\Payroll\TimeSheet - MYOB"
'contains folder path
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
Filename = Dir(folderPath & "*.xlsx")
Do While Filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & Filename)
wb.Sheets("Timesheet").Range("A9:N" & Range("A" &
Rows.Count).End(xlUp).Row).Copy
Workbooks("MYOBTimeSheetImport").Worksheets("MYOBTimeSheetImport").Range("A"
& Range("A" & Rows.Count).End(xlUp).Row + 1).PasteSpecial xlPasteValues
Workbooks(Filename).Close True
Filename = Dir
Loop
Application.ScreenUpdating = True
FPath = "C:\Users\preena.j\Documents\Payroll\TimeSheet - MYOB"
FName = "MYOBTimeSheetImport_" & Format(Now(), "YYYYMMDD")
Set NewBook = Workbooks.Add
ThisWorkbook.Sheets("MYOBTimeSheetImport").Copy Before:=NewBook.Sheets(1)
If Dir(FPath & "\" & FName) <> "" Then
MsgBox "File " & FPath & "\" & FName & " already exists"
Else
NewBook.SaveAs Filename:=FPath & "\" & FName, FileFormat:=xlCSV
End If
NewBook.Close savechanges:=True
End Sub
Example Timesheet File
Example Upload Template

Using the function at the link I posted, something like this (untested):
Option Explicit
Sub Consolidate()
Application.EnableCancelKey = xlDisabled
Dim folderPath As String
Dim Filename As String
Dim wb As Workbook
Dim FName As String
Dim FPath As String
Dim NewBook As Workbook
folderPath = "C:\Users\preena.j\Documents\Payroll\TimeSheet - MYOB"
'contains folder path
If Right(folderPath, 1) <> "\" Then folderPath = folderPath + "\"
Filename = Dir(folderPath & "*.xlsx")
Dim rngData, p, shtDest As Worksheet
Set shtDest = Workbooks("MYOBTimeSheetImport").Worksheets("MYOBTimeSheetImport")
Do While Filename <> ""
Application.ScreenUpdating = False
Set wb = Workbooks.Open(folderPath & Filename)
'<edited> range containing your data
With wb.Sheets("Timesheet")
Set rngData = .Range("A9:N" & _
.Range("A" & .Rows.Count).End(xlUp).Row)
End with
'</edited>
p = UnPivotData(rngData, 2, True, False) '<< unpivot
'put unpivoted data to sheet
With shtDest.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
.Resize(UBound(p, 1), UBound(p, 2)).Value = p
End With
Workbooks(Filename).Close True
Filename = Dir
Loop
Application.ScreenUpdating = True
FPath = "C:\Users\preena.j\Documents\Payroll\TimeSheet - MYOB"
FName = "MYOBTimeSheetImport_" & Format(Now(), "YYYYMMDD")
Set NewBook = Workbooks.Add
ThisWorkbook.Sheets("MYOBTimeSheetImport").Copy Before:=NewBook.Sheets(1)
If Dir(FPath & "\" & FName) <> "" Then
MsgBox "File " & FPath & "\" & FName & " already exists"
Else
NewBook.SaveAs Filename:=FPath & "\" & FName, FileFormat:=xlCSV
End If
NewBook.Close savechanges:=True
End Sub

Related

VBA - can not save as "xlsx" from "xlsm"

Me again , I'm trying to code for spliting sheets in the xlsm file into the seperate sheet then save them in the same place with the xlsm file. the code as below:
Sub splitsheet()
Dim path As String
Dim cities
ReDim cities(1 To ThisWorkbook.Worksheets.Count)
Dim i As Long
Dim sh As Worksheet
path = ActiveWorkbook.path
For i = 1 To Worksheets.Count
cities(i) = Sheets(i).Name
ActiveWorkbook.SaveAs _
Filename:=path & "\" & Sheets(i).Name & ".xlsx"
'ActiveWorkbook.Close False
Next i
End Sub
The error in my photo below. Why it can not save as in "xlsx" extension , above code is work fine with "xlsm" extension
Filename:=path & "\" & Sheets(i).Name & ".xlsm" 'it can work fine with xlsm extension
My question is how can save as in "xlsx" extension in this case. All assist/explaination will be appriciated.
Please try this code.
Sub EachSheetToEachOwnWorkbook()
' 286
Dim Path As String
Dim Ws As Worksheet
Application.ScreenUpdating = False
Path = ThisWorkbook.Path & "\"
For Each Ws In ThisWorkbook.Worksheets
Ws.Copy
With ActiveWorkbook
.SaveAs Filename:=Path & Ws.Name & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, _
CreateBackup:=False
.Close
End With
Next Ws
Application.ScreenUpdating = True
End Sub

How to open all files in the folder (xls and csv format files) - VBA

I have written code for consolidate the data from multiple workbook to one workbook and the code only opening the xls format files but some files have csv format in the folder. how to open csv and xls files in the folder? Any suggestion it would appreciated
Option Explicit
Sub ImportGroups()
Dim fPATH As String, fNAME As String
Dim LR As Long, LastRow As Long
Dim wb2, wb1 As Workbook, ofs As Worksheet
Set ofs = ThisWorkbook.Sheets("Sheet3")
fPATH = "C:\Users\ashokkumar.d\Desktop\MFI\"
fNAME = Dir(fPATH & "*.xls") 'get the first filename in fpath
Do While Len(fNAME) > 0
Set wb1 = Workbooks.Open(fPATH & fNAME) 'open the file
LastRow = ofs.Range("B" & Rows.Count).End(xlUp).Row
ofs.Range("B" & LastRow).Offset(1, -1).Value = fNAME
Sheets("Input").Range("C8:J12").Copy
ofs.Range("B" & LastRow).Offset(1, 0).PasteSpecial xlPasteValues
wb1.Close False 'close data workbook
fNAME = Dir 'get the next filename
Loop
LR = ofs.Range("C" & Rows.Count).End(xlUp).Row
ofs.Range("E2:I" & LR).Select
Selection.NumberFormat = "0.00%"
Application.ScreenUpdating = True
ofs.Range("A1:Z" & LR).Select
With Selection
WrapText = True
End With
End Sub
Just like this:
fNAME = Dir(fPATH & "*") 'get the first filename in fpath
Do While Len(fNAME) > 0
dim ext as string, p as integer
p = inStrRev(fName, ".")
ext = ucase(mid(fName, p+1))
if ext = "CSV" or ext = "XLS" or ext = "XLSX" or ext = "XLST" then
Set wb1 = Workbooks.Open(fPATH & fNAME) 'open the file
...
end if
You can get all Files in the Folder and check then if the file is an CSV or xlsx File. And then Open it like you did.
Option Explicit
Sub ImportGroups()
Dim fPATH As String, fNAME As String
Dim LR As Long, LastRow As Long
Dim wb2, wb1 As Workbook, ofs As Worksheet
Set ofs = ThisWorkbook.Sheets("Sheet3")
fPATH = "C:\Users\ashokkumar.d\Desktop\MFI\"
fNAME = Dir(fPATH & "*.*") 'get the first filename in fpath
Do While Len(fNAME) > 0
If Right(fNAME, 4) = "xlsx" Or Right(fNAME, 4) = ".csv" Then
Set wb1 = Workbooks.Open(fPATH & fNAME) 'open the file
LastRow = ofs.Range("B" & Rows.Count).End(xlUp).Row
ofs.Range("B" & LastRow).Offset(1, -1).Value = fNAME
Sheets("Input").Range("C8:J12").Copy
ofs.Range("B" & LastRow).Offset(1, 0).PasteSpecial xlPasteValues
wb1.Close False 'close data workbook
fNAME = Dir 'get the next filename
end if
Loop
LR = ofs.Range("C" & Rows.Count).End(xlUp).Row
ofs.Range("E2:I" & LR).Select
Selection.NumberFormat = "0.00%"
Application.ScreenUpdating = True
ofs.Range("A1:Z" & LR).Select
With Selection
WrapText = True
End With
End Sub

Convert only first worksheet XLSX files to CSV files

I would like to convert all XLSX files in a certain directory to CSV files. Each resulting CSV file should only contain the first worksheet of the XLSX file and be saved in a subfolder of the directory.
I am using the following script which works fine, except that it saves all worksheets as a separate CSV. I just need the first.
Could someone tell me how to modify the script? I have very little experience with VBA.
Sub Loop_Through_Files()
Dim WS As Excel.Worksheet
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Application.ScreenUpdating = False
Application.DisplayAlerts = False
myExtension = "*.xl??"
myPath = ActiveWorkbook.Path
myFile = Dir(myPath & "\" & "Input" & "\" & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Open workbook
Set x = Workbooks.Open(Filename:=myPath & "\" & "Input" & "\" & myFile)
SaveToDirectory = ActiveWorkbook.Path
For Each WS In x.Worksheets
WS.SaveAs SaveToDirectory & Left(x.Name, InStr(x.Name, ".") - 1) & "_" & WS.Name, xlCSV
Next
x.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Replace your for loop with this:
WS = x.Sheets(1)
WS.SaveAs SaveToDirectory & Left(x.Name, InStr(x.Name, ".") - 1) & "_" & WS.Name, xlCSV

Re-execute if the workbook exists or not using vba Excel

I want to execute, if the workbook exists already then re- run it if not exists then create a workbook.
I have uniques values(x) and array(names). I need to compare them if both are equal if not it has to create a workbook with name of array(names) that not had in uniques values(x)
My code:
Sub mac()
Dim c as integer
Dim x as range
Dim s_AgingSCM as string
Dim Array_SCM_Aging as variant
Dim NewBook as workbook
Dim NewBook_SCM as workbook
Dim Master_workbook as workbook
Dim rngCopy_Aging as range
Dim rngFilter_Ws2 as range
For c = LBound(Array_SCM_Aging) To UBound(Array_SCM_Aging)
Set Master_workbook = ThisWorkbook
s_AgingSCM = Array_SCM_Aging(c, 1)
Set x = Master_workbook.Sheets("BASS").Range("AY" & c)
If x = s_AgingSCM Then
With rngFilter_Ws2
.AutoFilter field:=32, Criteria1:="<>(a) 0 - 360", Operator:=xlFilterValues
.AutoFilter field:=37, Criteria1:=s_AgingSCM, Operator:=xlFilterValues
Set rngCopy_Aging = .SpecialCells(xlCellTypeVisible)
.AutoFilter ' Switch off AutoFilter
End With
rngCopy_Aging.Copy NewBook.Worksheets("Aging Inventory").Cells(1, 1)
Application.DisplayAlerts = False
Else
Dim fso: Set fso = createObject("Scripting.FileSystemObject")
Dim folder: Set folder = fso.GetFolder("C:\")
Dim file, fileNames
Dim rngCopy_SCMAging As Range
For Each file In folder.Files
If Right(file.Name, 4) = "xlsx" Then
fileNames = fileNames & file.Name & ";" ' will give a list of all filenames
End If
Next
If InStr(fileNames, s_AgingSCM) = 0 Then
With NewBook_SCM
Set NewBook_SCM = Workbooks.Add
.Title = s_AgingSCM
NewBook_SCM.Worksheets("sheet1").Name = "Aging Inventory"
With rngFilter_Ws2
.AutoFilter field:=32, Criteria1:="<>(a) 0 - 360", Operator:=xlFilterValues
.AutoFilter field:=37, Criteria1:=s_AgingSCM, Operator:=xlFilterValues
Set rngCopy_SCMAging = .SpecialCells(xlCellTypeVisible)
.AutoFilter ' Switch off AutoFilter
End With
rngCopy_SCMAging.Copy Destination:=NewBook_SCM.Worksheets("Aging Inventory").Cells(1, 1)
.SaveAs Filename:="KPI" & " " & s_AgingSCM & " " & Format_date & ".xlsx"
Application.DisplayAlerts = False
NewBook_SCM.Close
End With
' Else
End If
End sub
I was stuck here since 2 days. All i want is if the workbook exists then overwrite with the new workbook or else if its not exists create a new workbook.
Can someone please help me out.
A quick way to do it would be placing: -
If fso.FileExists(Application.DefaultFilePath & "\KPI" & " " & s_AgingSCM & " " & Format_date & ".xlsx")
fso.DeleteFile Application.DefaultFilePath & "\KPI" & " " & s_AgingSCM & " " & Format_date & ".xlsx", True
End If
Above the line
.SaveAs Filename:="KPI" & " " & s_AgingSCM & " " & Format_date & ".xlsx"
But this would not account for if the file could not be deleted (i.e. already open)

Excel Macro to save

I know i should probably be doing this in access or VB but I dont know how to use either. At the moment I have a submit button at the end of my form that saves and closes the workbook as whatever is inputted to a certain cell.
I am looking for a way to be able to do the same thing but break the worksheet out of the workbook. So it saves just the worksheet as its own excel file and with the name inputted into a certain cell. Below is the macro I am currently using.
Sub Saveworkbook()
Application.DisplayAlerts = False
Dim dName$, vName$
dName = Range("B8")
vName = ActiveWorkbook.FullName
ActiveWorkbook.SaveAs "W:\Test\" & dName
ActiveWorkbook.SaveAs vName
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
It would also be cool if it could add the date and computers user in to save name but not essential.
Thanks in advance
Sam
Something like this -
Sub SaveSheet()
Dim wbkDashboard As Workbook
Dim wsTarget As Worksheet
Set wsTarget = Thisworkbook.worksheets("Sheet1")
Dim strFileName As String
strFileName = wsTarget.Range("B8").Value _
& Format(Now, "ddmmyyyy") & "-" & Environ("username") & ".xlsx"
Set wbkDashboard = Workbooks.Add
wsTarget .Copy Before:=wbkDashboard.Sheets(1)
For intSheetCount = 2 To wbkDashboard.Sheets.Count
wbkDashboard.Sheets(2).Delete
Next
wbkDashboard.SaveAs "W:\Test\" & wsTarget.Range("B8").Value _
& Format(Now, "ddmmyyyy") & "-" & Environ("username") & ".xlsx"
wbkDashboard.Close
wsTarget.Range("B8").Value= strFileName
Set wsTarget = Nothing
Set wbkDashboard = Nothing
End Sub
This code will save any changes you have created in the current version, then it will save just the Active Sheet as a new workbook with the username and date (Credit to #Will on the Environment Variables).
Sub Saveworkbook()
Application.DisplayAlerts = False
Dim Sheet1 As Worksheet
Dim dName$, vName$, sName$
dName = Range("B8")
vName = ActiveWorkbook.FullName
sName = ActiveWorkbook.ActiveSheet.Name
For Each Sheet1 In ActiveWorkbook.Sheets
If Not Sheet1.Name = sName Then
Sheet1.Delete
End If
Next Sheet1
ActiveWorkbook.SaveAs "W:\Test\" & dName & "_" & Environ("username") & "_" & Format(Now, "ddmmyy") & "xlsx"
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub