I want to run through a specific sheet (from & to) save those ws as a new file in a folder, if the folder doesn't exist then create.
I'm able to do it to one sheet.
ActiveSheet.Next.Select
If Range("F3").Value = "" Then
Windows("Import OT.xlsm").Activate
Sheets("Cash").Select
Dim filename101 As String
Dim path101 As String
Application.DisplayAlerts = False
path101 = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
filename101 = Range("B1").Value & ".xlsx"
ActiveWorkbook.SaveAs path101 & Range("A2") & "\" & Range("A1") & " " & filename101,xlOpenXMLWorkbook
Application.DisplayAlerts = True
Else
Cells.Select
Range("F3").Activate
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Dim Path1 As String
Dim fpathname1 As String
Path1 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\"
fpathname1 = Path1 & Range("F3") & "\" & Range("F2") & " " & Range("B3") & ".xlsx"
path01 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & Range("F3")
Dim path001 As String
Dim Folder As String
Folder = Dir(path01, vbDirectory)
If Folder = vbNullString Then
VBA.FileSystem.MkDir (path01)
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
Else
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
End If
End If
End Sub
I want this as a loop is because I have a few tens of sheets. For it to work I think I need to write it specific time, but with loop I learned I don't need to do that.
Excel file sheet
https://onedrive.live.com/view.aspx?resid=AF6FF2618C09AC74!29027&ithint=file%2cxlsx&authkey=!AHcJjYCu8D0NTNY
According to your comment where you wrote the steps:
Read the comments
Try to run the code using F8 key and see where you need to change it.
As you're learning, please note to first write the steps in plain English Norsk and then develop your code.
See how I just followed your steps with readable code.
Code:
Public Sub GenerateCustomersFiles()
' 1) Active sheet (oppgjør 1-20)
Dim targetSheet As Worksheet
For Each targetSheet In ThisWorkbook.Sheets
' Check only sheets with string in name
If InStr(targetSheet.Name, "Oppgjør") > 0 Then
' 2) look if value in F3 is empty
If targetSheet.Range("F3").Value = vbNullString Then
' 3) if it is, do select "cash" sheet and save this file (its name and path are given above what it should be named)
Dim fileName As String
Dim filePath As String
Dim folderPath As String
folderPath = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
fileName = targetSheet.Range("B1").Value & ".xlsx"
filePath = folderPath & targetSheet.Range("A2") & "\" & targetSheet.Range("A1") & " " & fileName
ThisWorkbook.Worksheets("Cash").Select
ThisWorkbook.SaveAs filePath, xlOpenXMLWorkbook
Else
' 4) if it doesn't, do open selected sheet to a new workbook and save that in clients name folder (folder and path given above in code section)
folderPath = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & targetSheet.Range("F3")
fileName = targetSheet.Range("F2") & " " & targetSheet.Range("B3") & ".xlsx"
filePath = folderPath & "\" & fileName
' 5) check if clients folder exist or not for the file to be saved in.
' if folder doesnt exist,
' create new and save file there.
CreateFoldersInPath folderPath
' if folder exist just save the file there
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Add
targetSheet.Copy before:=targetWorkbook.Sheets(1)
targetWorkbook.SaveAs filePath, 51
targetWorkbook.Close
End If
End If
Next targetSheet
End Sub
' Credits: https://stackoverflow.com/a/31034201/1521579
Private Sub CreateFoldersInPath(ByVal targetFolderPath As String)
Dim strBuildPath As String
Dim varFolder As Variant
If Right(targetFolderPath, 1) = "\" Then targetFolderPath = Left(targetFolderPath, Len(targetFolderPath) - 1)
For Each varFolder In Split(targetFolderPath, "\")
If Len(strBuildPath) = 0 Then
strBuildPath = varFolder & "\"
Else
strBuildPath = strBuildPath & varFolder & "\"
End If
If Len(Dir(strBuildPath, vbDirectory)) = 0 Then MkDir strBuildPath
Next varFolder
'The full folder path has been created regardless of nested subdirectories
'Continue with your code here
End Sub
Let me know how it goes
Related
I create a new file every day that is named based on the previous business day
It looks like "mmddyyyy ENCORE and Floor". It's a csv file and I need to convert it to xlsm
This code successfully saves my file with the correct name and file type but I need it to save to a different place on my computer with folders based on months:
ActiveWorkbook.SaveAs Filename:="C:\Users\Sarajevo2022\Downloads\" & _
Format(Evaluate("Workday(today(),-2)"), "mmddyyyy") & _
" ENCORE and Floor", FileFormat:=52
The correct file path looks like this:
C:\Users\Sarajevo2022\Company Name\Coworker - OCC ENCORE\2022\Dec 2022
Any direction?
Save As Macro-Enabled Workbook
Sub SaveAsMacroEnabled()
' Build the folder path.
Dim FolderLeft As String: FolderLeft = "C:\Users\Sarajevo2022"
' or:
'Dim FolderLeft As String: FolderLeft = Environ("USERPROFILE")
Dim FolderMid As String: FolderMid = "\Company Name\Coworker - OCC ENCORE\"
Dim SaveDate As Date: SaveDate = Application.WorkDay(Date, -2)
Dim FolderRight As String: FolderRight = Format(SaveDate, "yyyy") _
& "\" & UCase(Format(SaveDate, "mmm yyyy")) & "\"
Dim FolderPath As String: FolderPath = FolderLeft & FolderMid & FolderRight
' Check if the folder path exists.
Dim PathExists As Boolean
With CreateObject("Scripting.FileSystemObject")
PathExists = .FolderExists(FolderPath)
End With
If Not PathExists Then
MsgBox "The path '" & FolderPath & "' doesn't exist!" _
& vbLf & vbLf & "File not saved!", vbCritical
Exit Sub
End If
' Build the file path.
Dim FilePath As String: FilePath = FolderPath _
& Format(SaveDate, "mmddyyyy") & " ENCORE and Floor" & ".xlsm"
' Return the paths in the Immediate window (Ctrl+G).
Debug.Print FolderPath & vbLf & FilePath
' After you have confirmed that the paths are correct,
' out-comment the previous and uncomment the next line.
'ActiveWorkbook.SaveAs FilePath, xlOpenXMLWorkbookMacroEnabled ' or 52
End Sub
I am a newbie in excel vba coding and trying to create pdf of a excel sheet range. My code works well in windows OS but somehow it doesn't work in Mac OS. The Code is as below:
`
Sub GeneratePDF()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim VelleName As String
Dim SelectedRange As Range
With ThisWorkbook.Worksheets("modulo")
.Activate
.Range(.Cells(1, 1), .Cells(33, 10)).Select
Selection.Name = "SelectedRange"
End With
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveWorkbook.Worksheets("modulo")
strTime = Format(Now(), "ddmmyyyy\_hhmm")
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
VelleName = ThisWorkbook.Worksheets("database").Range("B" & Desiredrow) & "_" & ThisWorkbook.Worksheets("database").Range("C" & Desiredrow)
'replace spaces and periods in sheet name
strName = Replace(VelleName, " ", "_")
strName = Replace(strName, ".", "_")
strName = Replace(strName, "-", "_")
strName = Replace(strName, "/", "_")
'create default name for savng file
strFile = strName & "_" & strTime & ".pdf"
strPathFile = strName & "_" & strTime
' select folder for file
If Dir(strPath & Application.PathSeparator & "forme", vbDirectory) = "" Then '<== check if folder exists but its not detecting even though i had created a folder there.
MkDir (ThisWorkbook.Path & Application.PathSeparator & "forme") '<== Create Folder and its not working for Mac OS.
End If
myFile = ThisWorkbook.Path & Application.PathSeparator & "forme" & Application.PathSeparator & strPathFile
'export to PDF if a folder was selected
If myFile <> "False" Then
With wsA.PageSetup
.Orientation = xlPortrait
.PrintArea = "SelectedRange"
.Zoom = False
.FitToPagesTall = 1
.FitToPagesWide = 1
End With
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "Il file pdf è stato creato: " _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Impossibile creare il file pdf"
Resume exitHandler
End Sub
`
I have tried searching a lot on internet but havent found any source which specifically teaches vba coding in Mac OS. Moreover, i got only one link https://macexcel.com/examples/filesandfolders/makefolder/ but i dont think it would work as it should be only one line of command and the biggest issue i dont have Mac OS available now. So can somebody test my code change my command to make it compatible it with Mac OS
I used to use this code and also add to check file exist
'Only Change code Here
Sub Verify()
Dim myPath As String
myPath = "C:\abc" '<--------This line
If Not PathExist(myPath) Then MkDir (myPath)
End Sub
Private Function PathExist(path_ As String) As Boolean
On Error GoTo ErrNotExist
Call ChDir(path_)
PathExist = True
Exit Function
ErrNotExist:
PathExist = False
End Function
Private Function FileExist(filePath_ As String) As Boolean
FileExist = Len(Dir(filePath_)) <> 0
End Function
I want to save Excel files in both the local drive and in the network folder. Currently I am doing it with SaveAs (local) and another SaveAs (network), is it faster to do a SaveAs then FileCopy?
Code below:
Sub SaveAs()
Dim ws As Worksheet
Dim ws_console As Worksheet
Dim long_col_number As Long
Dim long_sheets_count As Long
Dim arr_sheet_names As Variant
Dim str_password As String
Dim str_datetoday As String
Dim str_datetoday_path As String
Dim str_datetoday_network_path As String
str_datetoday = Format(Date, "yyyy-mm-dd")
str_datetoday_path = "C:\Users\" & Environ("Username") & "\Desktop\Report\" & str_datetoday
str_datetoday_network_path = "\\servername\data\reports\US Reports Daily\" & str_datetoday
If Dir(str_datetoday_path, vbDirectory) = "" Then
MkDir (str_datetoday_path)
MsgBox "Making directory"
End If
If Dir(str_datetoday_network_path, vbDirectory) = "" Then
MkDir (str_datetoday_network_path)
End If
For Each ws In ThisWorkbook.Worksheets
If ws.CodeName = "AILD_01_Console" Then
Set ws_console = ws
Exit For
End If
Next ws
long_col_number = 0
For long_col_number = 1 To 8
long_sheets_count = Application.WorksheetFunction.CountA(ws_console.Range(Cells(16, long_col_number), Cells(24, long_col_number)))
arr_sheet_names = ws_console.Range(Cells(16, long_col_number), Cells(15 + long_sheets_count, long_col_number))
arr_sheet_names = Application.WorksheetFunction.Transpose(arr_sheet_names)
Worksheets(arr_sheet_names).Copy
ActiveWorkbook.SaveAs _
Filename:=str_datetoday_path & "\" & ws_console.Cells(15, long_col_number) & " - " & Format(Date, "yyyy-mm-dd"), _
FileFormat:=51
ActiveWorkbook.SaveAs _
Filename:=str_datetoday_network_path & "\" & ws_console.Cells(15, long_col_number), _
FileFormat:=51
ActiveWorkbook.Close False
Next long_col_number
ws_console.Activate
End Sub
Thank you very much for all the help.
I am trying to get the following done. When I open workbook in folder, it opens, runs code where new copy of this workbook is created in "TEMP" folder and the original is closed. The idea is to have multiple copies open at the same time and on closing, all user updates copy into the original.
Everything works well when when workbook is opened second time, however on first opening when in Protected view I get Run-time error '91' Object variable or With block variable not set.
I have read a good bit about this issue but can't seem to figure it out.
Any help is much appreciated.
Private Sub Workbook_Open()
Dim strFilename, strDirname, strDirname2, strPathname, strDefpath As String
'Count files in folder
Dim MyFolder As String
Dim MyFile As String
Dim j As Integer
Dim strDefpatheee As String
Dim strDirnameeee As String
strDirnameeee = "TEMP"
strDefpatheee = Application.ActiveWorkbook.Path
MyFolder = strDefpatheee & "\" & strDirnameeee
MyFile = Dir(MyFolder & "\" & "*.xlsm")
Do While MyFile <> ""
j = j + 1
MyFile = Dir
Loop
'Save as same name + count of files in folder TEMP
On Error Resume Next ' If directory exist goto next line
strDirname = "TEMP" ' New directory name
strFilename = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5) & " " & j + 1 'New file name
strDefpath = Application.ActiveWorkbook.Path 'Default path name
'If IsEmpty(strDirname) Then Exit Sub
'If IsEmpty(strFilename) Then Exit Sub
'MkDir strDefpath & "\" & strDirname
strPathname = strDefpath & "\" & strDirname & "\" & strFilename 'create total string
ActiveWorkbook.SaveAs Filename:=strPathname & ".xlsm", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
Sheets("ACTIONS").Range("BG2").ClearContents
Sheets("ACTIONS").Range("D6").Select
PasswordEntry.Show
End Sub
How to copy the entire worksheet from a workbook and save it as new workbook to a specific directory with the customized filename(I am trying to pick the filename from on of the cells in the worksheet. The sheet that I need to copy has few merged cells too.
Sub CopyItOver()
Dim fname As String
Dim fpath As String
Dim NewBook As Workbook
Dim name as String
fpath = "C:\Users\..\"
fname = "List" & name & ".xlsm"
name = Range("c3").Value
Set NewBook = Workbooks.Add
ActiveWorkbook.Sheets("Generator").Copy Before:=NewBook.Sheets(1)
If Dir(fpath & "\" & fname) <> "" Then
MsgBox "File " & fpath & "\" & fname & " already exists"
Else
NewBook.SaveAs FileName:=fpath & "\" & fname
End If
End Sub
When I run this it, give me Subscript out of range error in this line
ActiveWorkbook.Sheets("Generator").Copy Before:=NewBook.Sheets(1)
Suggest you try it like this:
Check to see if Generator exists before progressing
If you use .Copy then the worksheet is automatically copied to a new workbook (so you don't need to add a new book first)
code
Sub CopyItOver()
Dim fname As String
Dim fpath As String
Dim name As String
Dim ws As Worksheet
fpath = "C:\Users\..\"
fname = "List" & name & ".xlsm"
name = Range("c3").Value
On Error Resume Next
Set ws = ThisWorkbook.Sheets("Generator")
On Error GoTo 0
If ws Is Nothing Then
MsgBox "sheet doesn't exist"
Exit Sub
End If
If Dir(fpath & "\" & fname) = vbNullString Then
ThisWorkbook.Sheets("Generator").Copy
ActiveWorkbook.SaveAs Filename:=fpath & "\" & fname
Else
MsgBox "File " & fpath & "\" & fname & " already exists"
End If
End Sub