VBA Excel Macro save as part of cell with date - vba

I have the following VBA code saving workbook1 sheets to a folder where workbook1 file is saved. Example: workbook1 has 31 sheets. The code saves each sheet to a new workbook with the same name as the sheet. (Sheet1, Sheet2, etc).
Sub SaveShtsAsBook()
Dim Sheet As Worksheet, SheetName$, MyFilePath$, N&
MyFilePath$ = ActiveWorkbook.Path & "\" & _
Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 4)
With Application
.ScreenUpdating = False
.DisplayAlerts = False
' End With
On Error Resume Next '<< a folder exists
MkDir MyFilePath '<< create a folder
For N = 1 To Sheets.Count
Sheets(N).Activate
SheetName = ActiveSheet.Name
Cells.Copy
Workbooks.Add (xlWBATWorksheet)
With ActiveWorkbook
With .ActiveSheet
.Paste
.Name = SheetName
[A1].Select
End With
'save book in this folder
.SaveAs Filename:=MyFilePath _
& "\" & SheetName & ".xls"
.Close SaveChanges:=True
End With
.CutCopyMode = False
Next
End With
Sheet1.Activate
End Sub
I need to modify the code to save the file with the ID and date. The ID is in cell A1. "XXX Clinic Pro Fees Report for Doe, John (JDOE)". In this example I need the new workbook to save as JDOE_2017-10-20.
Is there a way to gave the ID and place the date after it?

Try the below code
Sub SaveShtsAsBook()
Dim ldate As String
Dim SheetName1 As String
ldate = Format(Now(), "yyyy-mm-dd")
Dim Sheet As Worksheet, SheetName$, MyFilePath$, N&
MyFilePath$ = ActiveWorkbook.Path & "\" & _
Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 4)
With Application
.ScreenUpdating = False
.DisplayAlerts = False
' End With
On Error Resume Next '<< a folder exists
MkDir MyFilePath '<< create a folder
For N = 1 To Sheets.Count
Sheets(N).Activate
SheetName = ActiveSheet.Name
Cells.Copy
SheetName1 = Range(A1).Value2 & ldate
Workbooks.Add (xlWBATWorksheet)
With ActiveWorkbook
With .ActiveSheet
.Paste
.Name = SheetName
[A1].Select
End With
tempstr = Cells(1, 1).Value2
openingParen = InStr(tempstr, "(")
closingParen = InStr(tempstr, ")")
SheetName1 = Mid(tempstr, openingParen + 1, closingParen - openingParen - 1) & "_" & ldate
'save book in this folder
.SaveAs Filename:=MyFilePath _
& "\" & SheetName1 & ".xls"
.Close SaveChanges:=True
End With
.CutCopyMode = False
Next
End With
Sheet1.Activate
End Sub

You can extract the name code from within the brackets and append the date with a couple lines of code.
SheetName = Split(Split(.Cells(1, 1).Value2, "(")(1), ")")(0)
SheetName = sn & Format(Date, "_yyyy-mm-dd")
Along with a couple other modifications as,
Option Explicit
Sub SaveShtsAsBook()
Dim ws As Worksheet, sn As String, mfp As String, n As Long
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
On Error Resume Next '<< a folder exists
mfp = ActiveWorkbook.Path & "\" & Split(ThisWorkbook.Name, Chr(46))(0)
MkDir mfp '<< create a folder
On Error GoTo 0 '<< resume default error handling
With ActiveWorkbook
For n = 1 To .Worksheets.Count
With .Worksheets(n)
sn = Split(Split(.Cells(1, 1).Value2, "(")(1), ")")(0)
sn = sn & Format(Date, "_yyyy-mm-dd")
.Copy
With ActiveWorkbook
'save book in this folder
.SaveAs Filename:=mfp & "\" & sn, FileFormat:=xlExcel8
.Close SaveChanges:=False
End With
End With
Next
End With
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub

Related

VBA Export Sheets to Separate CSV Starting at Sheet 4 and beyond

as the title suggests, I'm trying to export sheets (starting from the fourth sheet and beyond, this is a fixed value) to separate CSV files. Ideally it would be right into a folder on the desktop containing each files. Below is the code I've been working with / trying to tweak-
Sub ExportSheetsToCSV()
Dim xWs As Worksheet
Dim xcsvFile As String
For Each xWs In Application.ActiveWorkbook.Worksheets
xWs.Copy
xcsvFile = CurDir & "\" & xWs.Name & ".csv"
Application.ActiveWorkbook.SaveAs Filename: = xcsvFile, _
FileFormat: = xlCSV, CreateBackup: = False
Application.ActiveWorkbook.Saved = True
Application.ActiveWorkbook.Close
Next
End Sub
Use the worksheets collection index.
Sub ExportSheetsToCSV()
Dim xWs As Worksheet
Dim xcsvFile As String, w as long
For w=4 to ActiveWorkbook.Worksheets.count
with ActiveWorkbook.Worksheets(w)
xcsvFile = CurDir & "\" & .Name & ".csv"
.Copy
with ActiveWorkbook
.SaveAs Filename:=xcsvFile, FileFormat:=xlCSV
.Close savechanges:=false
end with
end with
Next w
end sub
Is CurDir appropriate here? ActiveWorkbook.Path may be another option.

how to copy only values to new workbook

I am trying to copy only the values over from one workbook where calculations are done to another that holds all data. I have tried using .Value and xlPasteSpecial, but I think I'm using them incorrectly. I have limited VBA experience and am not a programmer.
Sub Consolidate()
Dim fName As String, fPath As String, fPathDone As String
Dim lr As Long, NR As Long
Dim wbData As Workbook, wsMaster As Worksheet
'Setup
Application.ScreenUpdating = False 'speed up macro execution
Application.EnableEvents = False 'turn off other macros for now
Application.DisplayAlerts = False 'turn off system messages for now
Set wsMaster = ThisWorkbook.Sheets("BM Condition") 'sheet report is built into
With wsMaster
If MsgBox("Clear the old data first?", vbYesNo) = vbYes Then
.UsedRange.Offset(1).EntireRow.Clear
NR = 2
Else
NR = .Range("A" & .Rows.Count).End(xlUp).Row + 1 'appends data to existing data
End If
'Path and filename (edit this section to suit)
fPath = "C:\Users\me\Desktop\Test" 'remember final \ in this string"
fPathDone = fPath & "Imported\" 'remember final \ in this string
On Error Resume Next
MkDir fPathDone 'creates the completed folder if missing
On Error GoTo 0
fName = Dir(fPath & "*.xls*") 'listing of desired files, edit filter as desired
'Import a sheet from found files
Do While Len(fName) > 0
If fName <> ThisWorkbook.Name Then 'don't reopen this file accidentally
Set wbData = Workbooks.Open(fPath & fName) 'Open file
'This is the section to customize, replace with your own action code as needed
lr = Range("A" & Rows.Count).End(xlUp).Row 'Find last row
Range("P14:S" & lr).EntireRow.Copy .Range("A" & NR).PasteSpecial xlPasteValues
wbData.Close False 'close file
NR = .Range("A" & .Rows.Count).End(xlUp).Row + 1 'Next row
' Name fPath & fName As fPathDone & fName 'move file to IMPORTED folder
End If
fName = Dir 'ready next filename
Loop
End With
ErrorExit: 'Cleanup
ActiveSheet.Columns.AutoFit
Application.DisplayAlerts = True 'turn system alerts back on
Application.EnableEvents = True 'turn other macros back on
Application.ScreenUpdating = True 'refreshes the screen
End Sub
I want only values from P14-S14. Can anyone assist with pulling only values from these cells?

Issue flattening Excel Files to a new folder using VBA

I currently have the following code. Currently this code will loop through a folder of excel files and will open them and then save them in that folder, but I can't get the code to then take those files flatten them and then place them into another folder. Any advice?
Sub ALoopFile()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.PrintCommunication = False
Dim MyFolder As String
Dim MyFile As String
Dim SendTo As String
Dim SendFile As String
Dim CurrentWB As Workbook 'Workbook Stores Workbook
MyFolder = "Y:\Dropbox (Efficiency3)\Monthly Projects\001 - AU"
MyFile = Dir(MyFolder & "\*.xls")
SendTo = "Y:\Dropbox (Efficiency3)\Monthly Projects\001 - AU\Flattened_Files"
SendFile = Dir(SendTo & "\*.xls")
Do While MyFile <> ""
Set CurrentWB = Workbooks.Open(Filename:=MyFolder & "\" & MyFile, UpdateLinks:=3) 'Sets CurrentWB = to that long name. This becomes the name of the workbook.
CurrentWB.RunAutoMacros Which:=xlAutoOpen 'Enables Macros in Workbook
CurrentWB.SaveAs Filename:=MyFolder & "\" & MyFile, FileFormat:=56
For SheetNumber = 1 To CurrentWB.Sheets.Count 'Counts Worksheets in Workbook
CurrentWB.Sheets(SheetNumber).Select 'Selects All Worksheets in Workbook
If (CurrentWB.Sheets(SheetNumber).Name <> "What If") Then
CurrentWB.Sheets(SheetNumber).Unprotect ("UMC626") 'Unprotects Workbook
Cells.Select 'Selects Data in Workbook
With CurrentWB.Sheets(SheetNumber).UsedRange
.Value = .Value
End With
CurrentWB.Sheets(SheetNumber).Protect Password:="UMC626", DrawingObjects:=True, Contents:=True, Scenarios:=True 'Protects Workbook
End If
Next SheetNumber 'Runs Through Iteration
Sheets(1).Select
Range("A1").Select 'Saves each workbook at the top of the page
CurrentWB.SaveAs Filename:=SendTo & "\" & SendFile, FileFormat:=56, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False 'Saves Workbook in Flatten File Location
CurrentWB.Close 'Closes Workbook
MyFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.PrintCommunication = True
End Sub
I solved the issue by using ThisName = CurrentWB.Name
ALoopFile()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.PrintCommunication = False
Dim MyFolder As String
Dim MyFile As String
Dim SendTo As String
Dim SendFile As String
Dim CurrentWB As Workbook 'Workbook Stores Workbook
MyFolder = "Y:\Dropbox (Efficiency3)\Monthly Projects\001 - AU\"
MyFile = Dir(MyFolder & "\*.xls")
SendTo = "Y:\Dropbox (Efficiency3)\Monthly Projects\001 - AU\Flattened_Files"
SendFile = Dir(SendTo & "\*.xls")
Do While MyFile <> ""
Set CurrentWB = Workbooks.Open(Filename:=MyFolder & "\" & MyFile, UpdateLinks:=3) 'Sets CurrentWB = to that long name. This becomes the name of the workbook.
CurrentWB.RunAutoMacros Which:=xlAutoOpen 'Enables Macros in Workbook
CurrentWB.SaveAs Filename:=MyFolder & "\" & MyFile, FileFormat:=56
ThisName = CurrentWB.Name
For SheetNumber = 1 To CurrentWB.Sheets.Count 'Counts Worksheets in Workbook
CurrentWB.Sheets(SheetNumber).Select 'Selects All Worksheets in Workbook
If (CurrentWB.Sheets(SheetNumber).Name <> "What If") Then
CurrentWB.Sheets(SheetNumber).Unprotect ("UMC626") 'Unprotects Workbook
Cells.Select 'Selects Data in Workbook
With CurrentWB.Sheets(SheetNumber).UsedRange
.Value = .Value
End With
CurrentWB.Sheets(SheetNumber).Protect Password:="UMC626", DrawingObjects:=True, Contents:=True, Scenarios:=True 'Protects Workbook
End If
Next SheetNumber 'Runs Through Iteration
Sheets(1).Select
Range("A1").Select 'Saves each workbook at the top of the page
CurrentWB.SaveAs Filename:=SendTo & "\" & ThisName
CurrentWB.Close 'Closes Workbook
MyFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.PrintCommunication = True
End Sub

Issue with VBA code when combining csv files as a workbook with separate sheets

I am having an issue with my code. I want to:
Combine multiple .csv files into 1 workbook with each .csv file as a separate sheet;
Shorten the sheet names(since they are too long with extra metadata;
Add a new sheet with the sheet names as hyperlinks to the sheets;
save the file as xlsx.
My problem is that when I step through the code or run it via alt+F8 it works fine, but when I use the shortcut it doesn't do anything but open the first .csv file. The macro is in the personal.xlsb location.
I am sure I could simplify my code so any suggestions are very welcome. Here is my code:
Sub CombineCsvFilesWithShortSheetLinks()
'ctrl+Shift+b
'Will ask you to open CSV files you wish to combine
Dim myDir As String, fn As String, wb As Workbook
Set wb = ActiveWorkbook
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show Then myDir = .SelectedItems(1) & "\"
End With
Application.ScreenUpdating = False
If myDir = "" Then Exit Sub
fn = Dir(myDir & "*.csv")
Do While fn <> ""
With Workbooks.Open(myDir & fn)
.ActiveSheet.Copy after:=wb.Sheets(wb.Sheets.Count)
.Close False
End With
fn = Dir
Loop
'save as
Dim workbook_Name As Variant
workbook_Name = Application.GetSaveAsFilename
If workbook_Name <> False Then
ActiveWorkbook.SaveAs _
Filename:=workbook_Name ', _
'FileFormat:=52(-4143 xlWorkbookNormal =Excel workbook file format.) 'I had issues with this line because it would just same a extensionless file, so my work around was to just type .xlsx at the end of my file name
End If
'List WS Name Rename Add Hyperlink
'Will shorten the sheet names and add a new sheet with a list of hyperlinks to each sheet
'list old names
Dim xWs As Worksheet
On Error Resume Next
Application.DisplayAlerts = False
xTitleId = "sheetnames"
Application.Sheets(xTitleId).Delete
Sheets("Sheet1").Select
Set xWs = Application.ActiveSheet
xWs.Name = xTitleId
For i = 2 To Application.Sheets.Count
xWs.Range("A" & (i - 1)) = Application.Sheets(i).Name
Next
Application.DisplayAlerts = True
'list new names'
selectworksheet = "sheetnames"
Range("B1").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-1],21,12)"
ActiveCell.Select
Selection.AutoFill Destination:=ActiveCell.Range("A1:A11")
ActiveCell.Range("A1:A11").Select
'rename'
selectworksheet = "sheetnames"
For i = 1 To 12
On Error Resume Next
oldname = Cells(i, 1).Value
newname = Cells(i, 2).Value
Sheets(oldname).Name = newname
Next
'create hyperlink page that Creates Links To All Sheets
Range("C1").Select
Dim cell As Range
For Each xWs In ActiveWorkbook.Worksheets
If ActiveSheet.Name <> xWs.Name Then
ActiveCell.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:= _
"'" & xWs.Name & "'" & "!A1", TextToDisplay:=xWs.Name
ActiveCell.Offset(1, 0).Select
End If
Next xWs
'save_workbook
ActiveWorkbook.Save
End Sub

Search Files using "if else" method based on User selection using drop down

I am relatively new to Visual Basic. I have VB macro code which searches files based on user selection using drop down menu and returns the value.
Below is the code snippet:
Sub GetDataFromClosedBook()
Dim mydata As String
Dim mydata1 As String
Dim wkb As Workbook
Dim wkb1 As Workbook
Application.EnableEvents = False
Application.ScreenUpdating = False
Sheets("Sheet1").Visible = True
Sheets("Sheet1").Select
' I need to add if else loop here,
' when 'mydata' is not found jump to 'mydata1'
' and return the value
mydata = "C:\Users\Desktop\Test\" & Range("A1") & Range("A2") & Range("A3") & Range("A4") & ".csv"
Set wkb = Workbooks.Open(mydata)
wkb.Sheets(1).Range("A1").Copy ThisWorkbook.Sheets("Sheet1").Range("C1")
wkb.Close False
mydata1 = "C:\Users\Desktop\Test\" & Range("B1") & Range("B2") & Range("B3") & Range("B4") & ".csv"
Set wkb1 = Workbooks.Open(mydata1)
wkb1.Sheets(1).Range("A1").Copy ThisWorkbook.Sheets("Sheet1").Range("C2")
wkb1.Close False
Sheets("Sheet1").Select
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Any help would be greatly appreciated!!
mydata = "C:\Users\Desktop\Test\" & Range("A1") & Range("A2") & Range ("A3") & Range("A4") & ".csv"
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(mydata)) Then
Set wkb = Workbooks.Open(mydata)
wkb.Sheets(1).Range("A1").Copy
ThisWorkbook.Sheets("Sheet1").Range("C1")
wkb.Close False
else
mydata1 = "C:\Users\Desktop\Test\" & Range("B1") & Range("B2") & Range("B3") & Range("B4") & ".csv"
Set wkb1 = Workbooks.Open(mydata1)
wkb1.Sheets(1).Range("A1").Copy
ThisWorkbook.Sheets("Sheet1").Range("C2")
wkb1.Close False
end if
Sheets("Sheet1").Select
Application.EnableEvents = True
Application.ScreenUpdating = True
I found another way to retrieve files based on dropdown selection Using Do while loop.
Here is the code Snippet.
Do While Filename <> ""
On Error Resume Next
Set wkb = Workbooks.Open(mydata & Filename)
wkb.Sheets(1).Range("D8").Copy ThisWorkbook.Sheets("Sheet1").Range("H6")
wkb.Close False
If Err.Number <> 0 Then
MsgBox ("Unable to open file " & Filename)
Err.Clear
End If
On Error GoTo 0
Exit Do
Filename = Dir
Loop