I need to check if a file exists on Sharepoint. If no, I want to save it: if it already exists, I want to save a copy of it
Sub save()
Dim newFile as string, fName as string, path as string
fName = Sheets(“Universe”).Cells(2,2).Value
newFile = fName & Format$(Date, “dd-mm-yyyy”)
path = “SharePoint URL”
If Len(Dir(path & newFile & “.xlsm”) = 0 Then
ActiveWprkbook.SaveAs Filename := path & newFile & “.xlsm”,
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:= False
Else
ActiveWprkbook.SaveAs Filename := path & newFile & “Copy” & “.xlsm”,
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:= False
End If
End sub
The first time the file is successfully saved; however, it always finds the If condition to be true and proceeds to overwrite the existing file.
How do I change the code such that it recognises when a file has been created and so makes of copy of it?
Maybe try this :
An example of path : "Z:Documents\Reports\2013\" would be "\\sharepoint\Documents\Reports\2013\"
Sub save()
Dim newFile As String, fName As String, path As String
fName = Sheets(“Universe”).Cells(2, 2).Value
newFile = fName & Format$(Date, “dd - mm - yyyy”)
path = “SharePoint URL”
myWorkbookBasePath = path & newFile & “.xlsm”
If Dir(myWorkbookBasePath, vbDirectory) = "" Then
ActiveWorkbook.SaveAs Filename:=myWorkbookBasePath, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else:
ActiveWorkbook.SaveAs Filename:=myWorkbookBasePath, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End If
End Sub
Note :
Make sure that your path end with a \
I Think ActiveWprkbook should be ActiveWorkbook
Related
I have facing an error while executing this code. If a file already exists in a destination folder it gives error. If a file does not exists it smoothly moves the files into the updated Date folder.
Can anyone please help so that in case if a file already exists in the destination folder the code does not give error. It can either replace the file with the new one or it can remain in the Source folder.
Sub moveAllFilesInDateFolder()
Dim DateFold As String, fileName As String
Const sFolderPath As String = "E:\Uploading\Source"
Const dFolderPath As String = "E:\Uploading\Archive"
DateFold = dFolderPath & "\" & Format(Date, "ddmmyyyy") ' create the folder if it does not exist
If Dir(DateFold, vbDirectory) = "" Then MkDir DateFold
fileName = Dir(sFolderPath & "\*.*")
Do While fileName <> ""
Name sFolderPath & "\" & fileName As DateFold & "\" & fileName
fileName = Dir
Loop
End Sub
This will be much appreciated.
Please, use this updated code. You cannot use Dir (once more) to check the file existence, because it will perturbate the existing loop. So, a VBScript object should be used. And naming will not be done, anymore. Name method is not able to overwrite an existing file:
Sub moveAllFilesInDateFolderIfNotExist()
Dim DateFold As String, fileName As String, objFSO As Object
Const sFolderPath As String = "E:\Uploading\Source"
Const dFolderPath As String = "E:\Uploading\Archive"
DateFold = dFolderPath & "\" & Format(Date, "ddmmyyyy") ' create the folder if it does not exist
If Dir(DateFold, vbDirectory) = "" Then MkDir DateFold
fileName = Dir(sFolderPath & "\*.*")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Do While fileName <> ""
If Not objFSO.FileExists(DateFold & "\" & fileName) Then
Name sFolderPath & "\" & fileName As DateFold & "\" & fileName
End If
fileName = Dir
Loop
End Sub
Is there a way of storing the directory found when using a wildcard? For example, if I have code that checks whether a directory exists:
Public Function DirectoryFinder(PartialFolderName As String)
Dim FilePath As String
If Dir(CurrentProject.Path & "\DataFolder\" & PartialFolderName & "*", vbDirectory)<>"" Then
'FilePath = ???
End If
End Function
Where the current project resides in C:\Folder and the desired full filepath is C:\Folder\DataFolder\PartialFolderName12345.
Is there a way to capture the directory found by the Dir() function within the FilePath variable? If I define FilePath as the following, I don't believe it captures the directory found:
FilePath=CurrentProject.Path & "\DataFolder\" & PartialFolderName & "*"
Rather, it sets FilePath equal to the string "C:\Folder\DataFolder\PartialFolderName*", which doesn't work for what I need.
What I want to be able to capture is the full "C:\Folder\DataFolder\PartialFolderName12345"
Something like this?
Sub Test()
Dim MyPath As String
MyPath = DirectoryFinder("SomeFolder123")
End Sub
Public Function DirectoryFinder(PartialFolderName As String) As String
Dim FilePath As String
FilePath = Dir(CurrentProject.Path & "\DataFolder\" & PartialFolderName & "*", vbDirectory)
If FilePath <> "" Then
DirectoryFinder = CurrentProject.Path & "\DataFolder\" & FilePath
End If
End Function
Assign the result of the Dir-function directly to the variable and check if it is empty or not:
Dim FilePath As String, BasePath as String
BasePath = CurrentProject.Path & "\DataFolder\"
FilePath = Dir(BasePath & PartialFolderName & "*", vbDirectory)
If FilePath <>"" Then
' FilePath now contains the name of the folder that was found.
' The full Path would be BasePath & FilePath
...
End If
Worth noting that vbDirectory will find both folders and files which match the supplied pattern, so you should consider making sure what you found was a folder and not a file. Also maybe allow for cases where >1 folders match your pattern.
Sub tester()
Dim folders As Collection
Set folders = MatchedDirectories("C:\Tester\", "tmp -*")
Debug.Print folders.Count
If folders.Count = 0 Then
'no matches
ElseIf folders.Count = 1 Then
'one match
Else
'multiple matches
End If
End Sub
Public Function MatchedDirectories(searchIn As String, PartialFolderName As String) As Collection
Dim f As String, col As New Collection
If Right(searchIn, 1) <> "\" Then searchIn = searchIn & "\"
f = Dir(searchIn & PartialFolderName, vbDirectory)
Do While Len(f) > 0
'make sure it's a directory we found...
If GetAttr(searchIn & f) = vbDirectory Then col.Add searchIn & f
f = Dir()
Loop
Set MatchedDirectories = col
End Function
I found some VBA routines here in and I tried to adapt them to my situation.
It works fine but when I try to copy a file to a folder that has been created using in its name a constant “process” and a variable [ID] field, I get an error message.
The error is in this line
FileCopy f.SelectedItems(i), "O:\docs\process\ " & (me.ID)
Private Sub Comando356_Click()
' lets say my current record has an ID field value 345
' The routine will check if folder O:\docs\process345 exists
' If the folder does not exist, then the folder is created:
If
Len(Dir("O:\docs\process" & (Me.ID), vbDirectory)) = 0 Then
MkDir "O:\docs\process" & (Me.ID)
End If
‘ So far it works perfectly: if the folder does not exist, is created
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
If f.Show Then
For i = 1 To f.SelectedItems.Count
sFile = Filename(f.SelectedItems(i), sPath)
' My problem is the next line: folder O:\docs\process345 exists but I get an error 76 “Path not Found”
FileCopy f.SelectedItems(i), "O:\docs\process" & (me.ID)
Next
End If
End Sub
Public Function Filename(ByVal strPath As String, sPath) As String
sPath = Left(strPath, InStrRev(strPath, "\"))
Filename = Mid(strPath, InStrRev(strPath, "\") + 1)
End Function
add a Slash and add the FileName
Private Sub Comando356_Click()
' lets say my current record has an ID field value 345
' The routine will check if folder O:\docs\process345 exists
' If the folder does not exist, then the folder is created:
If
Len(Dir("O:\docs\process" & (Me.ID), vbDirectory)) = 0 Then
MkDir "O:\docs\process" & (Me.ID)
End If
‘ So far it works perfectly: if the folder does not exist, is created
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
If f.Show Then
For i = 1 To f.SelectedItems.Count
sFile = Filename(f.SelectedItems(i), sPath)
' My problem is the next line: folder O:\docs\process345 exists but I get an error 76 “Path not Found”
' add some debugging
Debug.Print ("in=" & f.SelectedItems(i) & " out=" & "O:\docs\process" & (me.ID) & "\" & sFile)
' add a Slash and add the FileName
FileCopy f.SelectedItems(i), "O:\docs\process" & (me.ID) & "\" & sFile ' <<<<
Next
End If
End Sub
Public Function Filename(ByVal strPath As String, sPath) As String
sPath = Left(strPath, InStrRev(strPath, "\"))
Filename = Mid(strPath, InStrRev(strPath, "\") + 1)
End Function
I have this code that creates a folder and a saves the actual file in it, but i want that it only saves a copy with only one sheet in it. So that the file with the code works like a template...
You write your stuff and press the button and it saves an .xlsx file with one sheet (the sheet with the form) in the new created folder... so you could do this with hundreds of files an folders.
So in the end it should work like this:
You open the .xlsm file where the code below is in.
You got to sheets one FORM (what should be "exported" later on) and
a list where you copy stuff in the form.
When you filled the form and press the button and it saves the Form
sheet in the new folder as .xlsx and you can continue in the .xlsm
file.
If it's unclear for you please ask.
The code i have now
Sub Macro1()
Dim strFilename, strDirname, strPathname, strDefpath As String
On Error Resume Next ' If directory exist goto next line
strDirname = Range("D81").Value ' New directory name
strFilename = Range("D8").Value '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
End Sub
Problem here is i have Names for the forms that are like 1102,1103 an going on like that. the next step is that there are files with the name 1102_1 and 1102_2 and they both should go in the folder 1102 ...
It's a bit out of my knownledge please help me guys :) greets
Now i am using this code below
Problem is that it always closes the xlsm file what really annoyes and when i reopen it it wants to update the file i need to remove that but i don't know how :/... and it only should export/save one special sheet
Private Sub CommandButton1_Click()
Dim strFilename As String, _
strDirname As String, _
strPathname As String, _
strDefpath As String, _
SheetToExport As String, _
WbMaster As Workbook, _
WbCopy As Workbook
On Error Resume Next ' If directory exist goto next line
strDirname = Range("W12").Value ' New directory name
strFilename = Range("D8").Value 'New file name
Set WbMaster = Application.ActiveWorkbook
SheetToExport = Range("A1").Value 'Or specify UserForm output
strDefpath = WbMaster.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
WbMaster.Sheets(SheetToExport).Copy
Set WbCopy = Application.ActiveWorkbook
WbCopy.SaveAs Filename:=strPathname & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
WbCopy.Close
End Sub
Be careful on your variable declaration!
The way you did it in your OP (original post) :
strFilename, strDirname and strPathname are declared as Variant and not as String.
You can still use them BUT it'll take much more memory and can be issue if you use them as arguments.
See the code :
Dim strFilename As String, _
strDirname As String, _
strPathname As String, _
strDefpath As String, _
SheetToExport As String, _
WbMaster As Workbook, _
WbCopy As Workbook
On Error Resume Next ' If directory exist goto next line
strDirname = Range("D81").Value ' New directory name
strFilename = Range("D8").Value 'New file name
Set WbMaster = Application.ActiveWorkbook
SheetToExport = Range("A1").Value 'Or specify UserForm output
strDefpath = WbMaster.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
WbMaster.Sheets(SheetToExport).Copy
Set WbCopy = Application.ActiveWorkbook
WbCopy.SaveAs Filename:=strPathname & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
ClosingWb = MsgBox("Do you wish to close the exported file?",vbYesNo,"Close exported file")
If ClosingWb <> vbNo Then WbCopy.Close
How can I save the excel file using vba code so that the Username and Date are attached in a macro?
Here is the code that I worked on to try to make it work:
ActiveWorkbook.SaveAs FileName:=(Environ$("Username")) & "_" & Date & "_BKMtracker.xlsx", FileFormat:=xlOpenXMLWorkbook
Try this:-
ActiveWorkbook.SaveAs FileName:=(Environ$("Username")) & "_" & Date & "_BKMtracker.xlsx", FileFormat:=xlOpenXMLWorkbook
With credit to #MatthewD
Sub SaveDocument()
Dim username As String
Dim nowFormated As String
Dim path As String
Dim filename As String
Dim extention As String
username = Environ("Username") & "_" 'gets the username
nowFormated = CStr(Format(now, "yymmdd")) 'or every format you like
path = "D:\" 'Wherever you want to save the file
filename = "_BKMtracker" 'or what you want
extention = ".xlsm" 'for example (with macros, else you have to change the FileFormat too)
ActiveWorkbook.SaveAs filename:=path & username & nowFormated & filname & extention, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub