VBA to search for folder or create it - excel

good afternoon all,
i am using the following code on my spreadsheet to save the file in a specific folder with a specific format:
Const csPath As String = "C:\Stationery Orders\"
MyName = ActiveWorkbook.Name
ActiveWorkbook.SaveAs Filename:=csPath & Sheets("Stationery").Cells(1, 1) & Format(CStr(Now), "ddmmyyyy_hhmm") & " " & MyName & ".xlsm", FileFormat:=52
my problem is that i can't find a way to create this folder C:\Stationery Orders\ if the folder doesn't exist and also paste a shortcut on the user's desktop. Is that even possible? any ideas?
kind regards

Put a check before doing SaveAs. Something like,
If Dir(csPath, vbDirectory) = "" Then MkDir csPath
Then do the SaveAs

Try this. It will check if folder exists and create it if it doesn't exist.
Sub MyCuteSub()
Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FolderExists("C:\temp\temptemptemp") Then
FSO.CreateFolder ("C:\temp\temptemptemp")
End If
End Sub

Related

Saving Excel Files in a New Folder

I've been running into issues for a while with trying to save Excel files in new folders. I think that it's connected to OneDrive folders trying to sync, but I can't find anything that helps confirm this issue. I've included a sample piece of code that replicates the issue I've had. If I run this once (creating a new folder), then I will get a SaveAs error. But if I immediately run it again, it will just ask to overwrite the file and it will save just fine. Is there a way to go about handling the save as error or to continue to try until it's saved successfully?
Sub save_file()
Dim folder_path As String
folder_path = "C:\Users\" & Environ("USERNAME") & "\OneDrive - Company Name\Desktop\Test Folder"
If Len(Dir(folder_path, vbDirectory)) = 0 Then
MkDir (folder_path)
End If
Dim new_book As Workbook
Set new_book = Workbooks.Add
new_book.SaveAs Filename:=folder_path & "\Test Book", FileFormat:=51
End Sub
EDIT: I was able to find a potential workaround, although I haven't done much yet to test it. This file is still being saved to the folder, so I can close the file that gives the save error, and then just reopen it (here also setting it as the same Workbook object for reuse.
Sub save_file()
Dim folder_path As String
folder_path = "C:\Users\" & Environ("USERNAME") & "\OneDrive - Company Name\Desktop\Test Folder " & Format(Now, "HHMMSS")
If Len(Dir(folder_path, vbDirectory)) = 0 Then
MkDir (folder_path)
End If
Dim new_book As Workbook
Set new_book = Workbooks.Add
book_name = folder_path & "\Test Book " & Format(Now, "HHMMSS")
On Error GoTo savehandler
new_book.SaveAs Filename:=book_name, FileFormat:=51
Exit Sub
savehandler:
new_book.Close
Set new_book = Workbooks.Open(book_name)
End Sub

Excel VBA: how to check if a file exists using Administrative share path

I’m trying to create a deployment tool using excel and VBA.
The spreadsheet contains an Administrative share path i.e. (\\G5RCJ55\C$\users\public\desktop\file.txt)
I have administrative rights. I pull the path using VBA and tried using dir() but that fails.
Any suggestions on how I can:
1. Check if a file exists
2. If not, copy a file to the target machine/directory (The public desktop on the C: Drive).
Sub deployToDesktop(cnt As Integer)
Dim fullPath As String: fullPath = Cells(cnt, "D").value & "\" & Cells(cnt, "E").value
MsgBox ("Admin path " & fullPath)
If Not Dir(fullPath) Then
MsgBox (fullPath)
End If
End Sub
OK Found an answer. I need to use the FileSystemObject. This understands UNC path files.
Here is the updated code:
Sub deployToDesktop(cnt As Integer)
Dim fso As New FileSystemObject
Dim fullPath As String: fullPath = Cells(cnt, "D").value & "\"
If fso.FolderExists(fullPath) Then
MsgBox ("Exists " & fullPath)
End If
End Sub

How to open a .PDF file with wild card option via excel macro

Since I am very new to the excel macro I am trying to develop a code which is able to open the PDF file.But There are some PDF files in my system which are generated by another system therefore those files names change day by day and some figures are included too.
As an example,"Process Report 151120183569844" like this.These figures change everyday.I tried it with adding WILDCARD option but it doesn't work.How do I open this PDF with only a part of the file name?
Sub Open_PDF()
Dim pdfPath As String
pdfPath ="D:\Reports\Process Report*" & ".pdf" 'I used wildcard instead "Process Report 151120183569844"'
Call OpenAnyFile(pdfPath)
End Sub
Function openAnyFile(strPath As String)
Set objShell = CreateObject("Shell.Application")
objShell.Open(strPath)
End Function
As pointed out in another answer, the Dir function with a wildcard should do the trick.
Here's an example using the original openAnyFile function.
Sub Open_PDF()
Dim filePath As String, fileName As String
filePath = "D:\Reports\"
fileName = Dir(filePath & "Process Report*.pdf")
If fileName <> "" Then
openAnyFile filePath & fileName
End If
End Sub
Function openAnyFile(strPath As String)
Dim objShell As Object
Set objShell = CreateObject("Shell.Application")
objShell.Open (strPath)
End Function
You cannot open a file using a wildcard - it's just common sense, what if more than one file was matching your criteria - which one would you want to program to open? You have to specify the exact file name to open it.
if there is just one file in the target directory, you can use something like the following code to open it, regardless of its name:
sFound = Dir(ActiveWorkbook.Path & "\Process Report*.xlsm")
If sFound <> "" Then
Workbooks.Open filename:= ActiveWorkbook.Path & "\" & sFound
End If

Excel VBA: How to point to relative directory (name of the file changes a bit everyday)?

The current code is:
Set Workbook = Workbooks.Open("Z:\test\bankinfo20180815.xls")
The file in the folder would change. For example: it was bankinfo20180814.xls yesterday, bankinfo20180815.xls today and bankinfo20180816.xls tomorrow. So I am wondering how I can specify in VBA code to point to the file that starts with "bankinfo"?
Try this:
MyFile = "Z:\test\bankinfo"
Set Workbook = Workbooks.Open(MyFile & "*.xls")
Hope this helps!
You can use a wildcard like *, but if there are multiple files, it can open a wrong file so a better method is to make sure you are opening the exact file.
Sub OpenMyWB()
sdir = "Z:\test\"
sFile = Dir(sdir & "bankinfo" & Format(Date, "yyyymmdd") & ".xls")
Set wb = Application.Workbooks.Open(sdir & sFile)
End Sub

Create a folder in My Documents and save a workbook to that folder

I created an Excel Add-In that is used on a workbook with imported data. I need to add code that will do the following:
Check if folder exists C:\Users\\My Documents\ Extract
Files\
Create the folder if it does not exist
Save the file into this folder with current date and time (Now) in the file name with an .xlsx extension.
Example: C:\Users\jdoe\My Documents\Extract Files\Extract - 01-15-2016 15:15.xlsx
I have found this, but need to know how to get my criteria above into this code:
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=xlOpenXMLWorkbook
I do not know enough about VBA to create a folder if it does not exist (if you can do this with VBA). I have looked but could not find anything that was helpful. Asking for some guidance here. Thanks.
Try this code:
Sub Ex()
If InStr(LCase$(ActiveWorkbook.name), "extract") > 0 Then
Exit Sub
Else
Dim MyDir As String, fn As String
MyDir = CreateObject("WScript.Shell").SpecialFolders("MyDocuments") & "\Extract Files" ' change this to valid path
If Len(Dir(MyDir, vbDirectory)) = 0 Then MkDir MyDir
fn = MyDir & "\Extract - " & Format(Now, "mm-dd-yyyy hh_mm")
ActiveWorkbook.SaveAs Filename:=fn, FileFormat:=xlOpenXMLWorkbook
End If
End Sub
we can not use : in the file name
Give this a try:
Sub dural()
Dim folder As String, myFileName As String
folder = "C:\TestFolder\Extract Files"
On Error Resume Next
MkDir folder
On Error GoTo 0
myFileName = folder & "\" & "Extract - " & Format(Now, "mm-dd-yyyy hh mm") & ".xlsx"
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=xlOpenXMLWorkbook
End Sub
after changing the folder name.................if you get a warning, click on the yes button
The macro will create the folder if it does not exist.

Resources