PDA

View Full Version : VBA to create folder and Save As the file



megha
09-27-2010, 08:43 AM
I am quite new to VBA and need a help with my code. I actually have a excel file with command button that will stamp the current date and time then save as the file to the specific location. It works fine.

I want to add a code that will create a folder every month to that same location and named the folder “Aug 2010, Sept 2010, Oct 2010, etc.” and save as the file with current date and time into appropriate folder. Thanks for you help in advance. I have copied the code which i am using now.



Private Sub CommandButton1_Click()
Dim sFileName As String
Dim sPath As String

CommandButton1.Enabled = False

sFileName = Format(DateValue(Now()), "mmm_dd_yyyy") & "_" & _
Format(TimeSerial(Hour(Now()), Minute(Now()), Second(Now())), "hh_mm_ss_AM/PM")
sPath = "http://sptdsrefining. (http://sptdsrefining.conocophillips.net/sites/Bayway/op/All)"
sFileName = sFileName & ".xls"
ActiveWorkbook.SaveAs Filename:=sPath & sFileName, FileFormat:=xlNormal, ReadOnlyRecommended:=False
ThisWorkbook.Close SaveChanges:=False
End Sub

Simon Lloyd
09-27-2010, 09:08 AM
perhaps something like this? (not tested)
Private Sub CommandButton1_Click()
Dim sFileName As String
Dim sPath As String
CommandButton1.Enabled = False
sFileName = Format(DateValue(Now()), "mmm_dd_yyyy") & "_" & _
Format(TimeSerial(Hour(Now()), Minute(Now()), Second(Now())), "hh_mm_ss_AM/PM")
If Len(Dir("C:\MYDIRECTORY\" & Format(DateValue(Now()), "mmm_yyyy"), vbDirectory)) = 0 Then
MkDir "C:\MYDIRECTORY\" & Format(DateValue(Now()), "mmm_yyyy")
End If
sPath "C:\MYDIRECTORY\" & Format(DateValue(Now()), "mmm_yyyy")
sFileName = sFileName & ".xls"
ActiveWorkbook.SaveAs Filename:=sPath & "\" & sFileName, FileFormat:=xlNormal, ReadOnlyRecommended:=False
ThisWorkbook.Close SaveChanges:=False
End Sub