I have a macro-enabled workbook, that has a macro that should save a copy of the file to a new location. I store the name of the original file as a string before saving to the new location, so that I can still reference the original file in the original location. The file still exists there, and the filename string works when I open the file using it, but it doesn't work when I try to do anything else with the string.
The original location is a folder called Source, and the file is copied to the folder called Destination.
The important problem here, is that the folders are located on SharePoint. If the folders are on a local machine it's not an issue.
https://[company].sharepoint.com/sites/[team]/Shared Documents/General/Source/oldVersion.xlsm
https://[company].sharepoint.com/sites/[team]/Shared Documents/General/Destination/newVersion.xlsm
Sub testMove()
FullName = Application.ActiveWorkbook.FullName
ActiveWorkbook.SaveAs "https://[company].sharepoint.com/sites/" _
& "[team]/Shared Documents/General/Destination/newVersion.xlsm", xlOpenXMLWorkbookMacroEnabled
'SetAttr FullName, vbNormal
Workbooks.Open FullName
End Sub
The above code runs just fine, but when you uncomment the setAttr it gets a file not found error.
The goal is to be able to close and/or delete the file in the original location, so SaveCopyAs doesn't quite work for this purpose.
SaveAs and Delete
This works for me. Your feedback is most welcome.
Option Explicit
Sub TestMove()
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sFilePath As String: sFilePath = wb.FullName
Dim dFilePath As String: dFilePath = "C:\Users\[username]\OneDrive\" _
& "Documents\Destination\newVersion.xlsm"
Application.DisplayAlerts = False ' overwrite without confirmation
wb.SaveAs dFilePath, xlOpenXMLWorkbookMacroEnabled
Application.DisplayAlerts = True
'Debug.Print wb.Name ' to prove that it has a new name now
If Len(Dir(sFilePath)) > 0 Then
SetAttr sFilePath, vbNormal
Workbooks.Open sFilePath
'Or:
'Kill sFilePath
Else
MsgBox "File not found.", vbCritical
End If
End Sub
Related
I have spent my whole morning on this and cannot get it working properly. A simple Excel userform was created asking for a filename. If the file exists in the directory I want it to open. If it does not exist I want a "template" file opened instead. I have the does not exist working properly, however cannot get the "does exist" part working. Please help.
Private Sub CmdEnter_Click()
Dim Path As String
Dim File As String
Path = Range("Search!B1")
File = TxtOrder.Value
'If File exists then open.
If Dir(Path & File & ".xlsm") = Path & File & ".xlsm" Then
Workbooks.Open FileName:=Path & File & ".xlsm"
'If File does not exist then open.
ElseIf Dir(Path & File & ".xlsm") = Error Then
Workbooks.Open FileName:=Path & "QCSFormTrial.xlsm"
End If
'Close Dialog and Close Workbook
Workbooks("QCSLaunch.XLSM").Close SaveChanges:=False
End Sub
Please, try this way:
Private Sub CmdEnter_Click()
Dim Path As String, File As String, wb As Workbook
Path = Range("Search!B1")
File = TxtOrder.value
'If File exists then open.
If dir(Path & File & ".xlsm") <> "" Then
Set wb = Workbooks.Open(Path & File & ".xlsm")
Else 'else, open the other one:
Set wb = Workbooks.Open(Path & "QCSFormTrial.xlsm")
End If
Stop 'check if the workbook has been open and press F5 to let code finishing
wb.Close SaveChanges:=False
End Sub
The issue is that Dir(Path & File & ".xlsm") = Path & File & ".xlsm" is basically saying does the folder path I named equal the folder path I named. The path isn't actually directed at the actual folder in way that will open it.
Try this: https://exceloffthegrid.com/vba-code-loop-files-folder-sub-folders/
Sub LoopAllFilesInAFolder()
'Loop through all files in a folder
Dim fileName As Variant
fileName = Dir("C:\Users\marks\Documents\")
While fileName <> ""
'Insert the actions to be performed on each file
'This example will print the file name to the immediate window
Debug.Print fileName
'Set the fileName to the next file
fileName = Dir
Wend
End Sub
Or, you can remove the If Then and directly open the file. If the file exists, it will open, if not, it will error. You can use error handling then continue.
I'm trying to write a code that will refresh all workbooks starting with 'FY' in a folder. With the current code, the first two workbooks refresh, but when it comes to the third workbook, I get this error:
Sorry, we couldn't find FY20 11-15.xlsm\FY20 1-5.xlsm. Is it possible it was moved, renamed or deleted?"
The path to the workbook is "C:\Documents\Database\Sales".
Here's the code:
Sub refreshdata()
Dim file As String
Dim book As String
file = Application.ThisWorkbook.Path
book = Dir(file & "\FY*.xlsm")
Do While file <> ""
Dim wb As Workbook
Set wb = Workbooks.Open(file & "\" & book)
Call Refresh
wb.Close savechanges:=True
file = Dir
Loop
End Sub
You named your variables not clearly and file contains actually a path file = Application.ThisWorkbook.Path therefore you mixed everything up. Get your variable names more meaningful! Make sure your variables are well named after what content they contain or you confuse yourself.
Sub refreshdata()
Dim Path As String
Path = Application.ThisWorkbook.Path
Dim FileName As String
FileName = Dir(Path & "\FY*.xlsm")
Do While FileName <> vbNullString
Dim wb As Workbook
Set wb = Workbooks.Open(Path & "\" & FileName)
Call Refresh
wb.Close SaveChanges:=True
FileName = Dir
Loop
End Sub
What was wrong?
Here file = Dir you set your file variable which actually was the path to filename. And in the next iteration of the loop Set wb = Workbooks.Open(file & "\" & book) is twice a filename, the new filename in file and the old in book.
Background Information - I have two buttons, that both run a set of code. The excel file has over 30 columns and 65,000 rows. This file is exported (.csv) from somewhere and is updated biweekly.
Goal - have the new file saved with the same name as the old. So that the values can be updated, buttons are still available and the code can run again with the new file.
Or That when a new file is exported, it is saved in a folder that runs the code INDEPENDENT of the user path. i.e Pathname = ActiveWorkbook.Path & "C:\Users\"this can be any name"\Desktop\Downloads\"
Attempt
Used a similar code to the one in a previous question "Run same excel macro on multiple excel files" with edits to tailor for my code. With no success
Sub ProcessFiles()
Dim Filename, Pathname As String
Dim wb As Workbook
Pathname = ActiveWorkbook.Path & "\Files\"
Filename = Dir(Pathname & "*.xls")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
DoWork wb
wb.Close SaveChanges:=True
Filename = Dir()
Loop
End Sub
Currently, when I attempt the first method I only replace (Old file + VBA) with (New file).
Please note that the solution does not need to be a VBA code. If it's just saving the file in a new method that stores the macro and updates the values I would be happy.
An example of my previous answer:
Sub SaveThisAs()
Dim wb As Workbook: Set wb = ThisWorkbook 'ThisWorkbook referrs to the workbook the macro is ran from
Dim PathToSaveTo As String
PathToSaveTo = wb.Path & "\"
PathToSaveTo = PathToSaveTo & Format(Now, "ddMMyyyy_hhmmss") & wb.Name 'Lets add a timestamp
'Do your macro stuff here
'....
'Save the workbook
wb.SaveAs PathToSaveTo
End Sub
Please note that I'm using wb.Name at the end of the file to save to... this will be fine first time you run this, but a second time the name will get longer... and longer ... and longer. Adjust as per your needs with an appropriate file name.
I do the following -
Sub SaveCopy()
Set xls = CreateObject("Excel.Application")
'xls.DisplayAlerts = False
'Application.DisplayAlerts = False
Dim CurrentFile As String
CurrentFile = ThisWorkbook.FullName
ThisWorkbook.SaveAs Filename:=Replace(ThisWorkbook.FullName, "xlsm", "xls"), FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Sheets("Settings").Delete
ActiveWorkbook.Close SaveChanges:=True
Application.Workbooks.Open Filename:=CurrentFile
xls.DisplayAlerts = True
Application.DisplayAlerts = True
End Sub
This code has the following problems:
When I open the result file, it says that the file format is not equal to the file content
It doesn't open the original book again (Application.Workbooks.Open line is not executed)
How can I fix it?
You could do something like this:
Sub SaveCopy()
Dim CurrentFile As String
CurrentFile = ThisWorkbook.FullName
ThisWorkbook.SaveAs Filename:=Replace(ThisWorkbook.FullName, "xlsm", "xlsx"), FileFormat:=xlOpenXMLWorkbook
ThisWorkbook.Sheets("Settings").Delete
Application.Workbooks.Open Filename:=CurrentFile 're-open original file
ThisWorkbook.Close SaveChanges:=True
'The line above will terminate this macro immediately
'Everything beyond this line will not execute.
End Sub
Note that if the workbook CurrentFile has a Workbook_Open event, that this will also immediately be terminated when ThisWorkbook.Close runs.
A more save alternative is to use the Workbook.SaveCopyAs method.
Advantage is, that this method keeps the original workbook open and just saves a copy.
Disadvantage is that .SaveCopyAs cannot change the file type, because it does not support the parameter FileFormat:=.
That means you must save a copy in the same file format first, then open that copy and save it again with .SaveAs to change the file format and then delete the temporary copy.
Sub SaveCopyAdvanced()
Dim CurrentFile As String
CurrentFile = ThisWorkbook.FullName
Dim CopyFileName As String
CopyFileName = Replace(ThisWorkbook.FullName, ".xlsm", "_COPY.xlsm")
'save a temporary copy but keep the original workbook unchanged and open
ThisWorkbook.ActiveWorkbook.SaveCopyAs Filename:=CopyFileName
Dim CopiedWb As Workbook
Set CopiedWb = Application.Workbooks.Open(Filename:=CopyFileName)
CopiedWb.Sheets("Settings").Delete
'convert filename to xlsx
CopiedWb.SaveAs Filename:=Replace(ThisWorkbook.FullName, "xlsm", "xlsx"), FileFormat:=xlOpenXMLWorkbook
'close it (we already saved it)
CopiedWb.Close SaveChanges:=False
'kill temporary file with _COPY
Kill CopyFileName
End Sub
It is supposed to open the file, save as, copy values, Save as again (final filename), then to delete the first save as. I am using this to achieve a temporary .xlsx file. It works, opens, saves as window comes up, then deletes the Temp file but it is not saving the file before it deletes the temp file.
Code:
Sub PracticeMakesPerfect()
Dim wbMain As Workbook
Dim Alpha As Workbook
Dim Beta As Workbook
Dim sFile As String
Dim PurgeTemp
Application.DisplayAlerts = False
Set wbMain = Workbooks("Macro Tester.xlsm")
Set Alpha = Workbooks.Open("C:\Users\frfcomputer\Desktop\Test.xlsx")
ActiveWorkbook.SaveAs "C:\Users\frfcomputer\Desktop\test\Temp.xlsx"
Set Beta = Workbooks("Temp.xlsx")
wbMain.Sheets("Sheet1").Range("A1").Value = Beta.Sheets("Sheet1").Range("A1").Value
Application.DisplayAlerts = True
Application.GetSaveAsFilename
ActiveWorkbook.Close
'Source File Location
sFile = "C:\Users\frfcomputer\Desktop\test\" & "Temp.xlsx"
'Sets Object
Set PurgeTemp = CreateObject("Scripting.FileSystemObject")
'Checks File Exists or Not
If PurgeTemp.FileExists(sFile) Then
'If file exists, delete the file
PurgeTemp.DeleteFile sFile, True
MsgBox "Deleted The File Successfully", vbInformation, "Done!"
Else
'If file does not exists
MsgBox "Specified File Not Found", vbInformation, "Not Found!"
End If
End Sub
You're asking for a filename to save as with Application.GetSaveAsFilename but you're not putting it to use:
Sub test()
Dim a As String
a = Application.GetSaveAsFilename(FileFilter:="Excel Files, *.xls") 'Ask for a filename to save as.
ThisWorkbook.SaveAs a 'Save the file
End Sub
It's the end of the day, so haven't added everything - check that the result of a isn't FALSE or some other unusable name. There's also various options available under SaveAs.