What is the equivalent of this code for MacOS excel? - excel

Can someone advise the equivalent code to use in Excel for Mac that would create the same result as the below does in Windows?
Path = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\"
ActiveWorkbook.SaveAs Path & "CAD DATA.xlsx"

Use something like the following function
Function GetDesktopPath() As String
#If Mac Then
GetDesktopPath = Mid(MacScript("tell application ""Finder""" & vbLf & "return desktop as alias" & vbLf & "end tell"), 7)
#Else
GetDesktopPath = CreateObject("WScript.Shell").SpecialFolders("Desktop")
#End If
End Function
in your code to make it work on both Mac and Windows
Path = GetDesktopPath & Application.PathSeparator
ActiveWorkbook.SaveAs Path & "CAD DATA.xlsx"
Make sure ActiveWorkbook is actually what you want to use. You probably meant to use ThisWorkbook:
ActiveWorkbook is the workbook that has the focus (is on top) while this code runs. This can easily change by a simple mouse click or any other interference.
ThisWorkbook is the workbook this code runs at. This is much more reliable because it never changes by any user interaction.
① Source of the MacScript: http://www.vbaexpress.com/forum/showthread.php?54852-Returning-the-Desktop-Path

Related

ActiveWorkbook.SaveAs not being able to run

This is probably a really simple task, but for some reason my code doesnt run. This code has worked for the past few months but when I initiate the command now it doesnt work.
The code that I had used (without any change) is the following:
Sub Copy()
ActiveWorkbook.SaveAs "C:\Users\[File Location]" & "File Name " & Format(Now(), "DD-MMM-YYYY") & ".xlsm", FileFormat:=52
End Sub
Wondering if anyone could provide any advice / tips on how to solve/troubleshoot >.< many thanks in advance.
Here it is broken up a little for you. The Environ() function just gets the user name of whoever is logged in when the code runs.
Replace how File1 is created if you want something else. (you did not include that part in your question)
Sub SaveIt()
Dim SavePath As String
Dim File1 As String
Dim Filename As String
SavePath = "C:\Users\" & Environ("UserName") & "\Desktop\TRD\Run\"
File1 = Split(ActiveWorkbook.Name, ".")(0) ' strip out the file extension
Filename = File1 & " " & Format(Now(), "DD-MMM-YYYY") & ".xlsm"
ActiveWorkbook.SaveAs SavePath & Filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
Note: This assumes the folder you are saving it to exists already.

adding a sub folder using activeworkbook.path syntax

ok so this is a short peace in a big workbook... All i am trying to do is tell it a certain place to save.
ActiveWorkbook.SaveCopyAs _
FileName:=ActiveWorkbook.Path "\OLD " & Range("D1").Value & ".XLSM"
This does exactly as it is supposed to however, i want to say basically
"activeworkbook.path" plus give it one further step and designate a folder called "old" that it will go to.
in essence it would look like this
\documents\test\my-file.xlsm
to this
\documents\test\OLD\my-file.xlsm
any hints?
You have a space in "\OLD ", and you are not closing off \OLD to be a folder.
The line should look like
ActiveWorkbook.SaveCopyAs _
FileName:=ActiveWorkbook.Path & "\OLD\" & Range("D1").Value & ".XLSM"
I would also strongly consider qualifying your Range("D1") with your worksheet.
Dim fileNameRng as range
Set fileNameRng = thisworkbook.worksheets("Sheet1").Range("D1")
ActiveWorkbook.SaveCopyAs _
FileName:=ActiveWorkbook.Path & "\OLD\" & fileNameRng.Value & ".XLSM"

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 general path for shared file

I'm trying to use file dialogue to pick a file and save it to a folder but I can't figure out how to code a folder path and keep getting "Path not found error"
I'm not at all a coder, so please explain in plain English:)
Below is the piece of code I tried to use but didn't work.
ArchiveFolderPath = Environ("UserDomain") & "\" & Environ("username") & "\Desktop"
Full sub code from comment below:
Sub CreateCopyFile(FilePathToCopy As String)
Dim fso As Scripting.FileSystemObject
Dim FileToCopy As Scripting.File
Dim ArchiveFolderPath As String
'Create a new folder path
Set fso = New Scripting.FileSystemObject
ArchiveFolderPath = Environ("UserProfile") & "\Desktop\Archive"
'Create a new folder
If Not fso.FolderExists(ArchiveFolderPath) Then
fso.CreateFolder ArchiveFolderPath
End If
Set FileToCopy = fso.GetFile(FilePathToCopy)
FileToCopy.Copy ArchiveFolderPath & "\" & FileToCopy.name
Set fso = Nothing
End Sub
Try adding another backslash at the end of the word, "Desktop", and add two backslashes at the very beginning of the path. Like so:
ArchiveFolderPath = "\\" & Environ("UserDomain") & "\" & Environ("username") & "\Desktop\"
You need to put another \ at the end of Desktop and then make sure that you put the file name after it when you are saving.
So will look like ArchiveFolderPath = Environ("UserDomain") & "\" & Environ("username") & "\Desktop\"
Some of what you are looking for is going to depend on the operating system. In Windows 7, there is a Public Desktop that populates all user desktops and has fairly open file permissions. It is located at:
c:\Users\Public\Desktop
If that is where you want to put things then your code would be one of these,
ArchiveFolderPath = "c:\Users\Public\Desktop"
ArchiveFolderPath = Environ("PUBLIC") & "\Desktop"
If you wanted to point to the current users desktop then that would be one of these,
ArchiveFolderPath = "c:\Users\" & Environ("USERNAME") & "\Desktop"
ArchiveFolderPath = Environ("USERPROFILE") & "\Desktop"
The environment variable that you are using (`Environ("USERDOMAIN")) typically points to the computer name in a workgroup environment although it would be different in a structured Active Directory network.
Remember to use environment variables whenever possible to avoid variations in hard-coded paths between system operating versions. An XP machine's user profiles are not in the same place as a Windows 7 or Windows 8 machine.
A quick and easy way to get a list of the environment variables in the current session is to open a command prompt window and type SET then hit Enter.

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

I have an Excel Workbook that on form button click I want to save a copy of the workbook with the filename being the current date.
I keep trying the the following
ActiveWorkbook.SaveAs ("\\filePath\FormFlow To MSExcel\" & Left(Now(), 10)) but am receiving Run-time error '1004': Method 'SaveAs' of object'_Workbook' failed.
Can anyone assist me with this? I'm still very new to developing for Excel.
Most likely the path you are trying to access does not exist. It seems you are trying to save to a relative location and you do not have an file extension in that string. If you need to use relative paths you can parse the path from ActiveWorkbook.FullName
EDIT:
Better syntax would also be
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=xlWorkbookNormal
Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'
Stop recording and you can start inspecting your code.
I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"
Option Explicit
Sub SaveFile()
Dim fdate As Date
Dim fname As String
Dim path As String
fdate = Range("A1").Value
path = Application.ActiveWorkbook.path
If fdate > 0 Then
fname = "Event " & fdate
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
MsgBox "Chose a date for the event", vbOKOnly
End If
End Sub
Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!
It could be that your default format doesn't match the file extension. You should specify the file format along with the filename, making sure the format matches the extension:
With someWorkbook
.SaveAs "C:\someDirector\Awesome.xlsm", fileformat:=xlOpenXMLWorkbookMacroEnabled
End With
OTOH, I don't see an extension on your .SaveAs filename. Maybe you need to supply one when doing this programmatically. That makes sense--not having to supply an extension from the GUI interface is convenient, but we programmers are expected to write unambiguous code. I suggest adding the extension and the matching format. See this msdn page for a list of file formats. To be honest, I don't recognize a lot o the descripions.
xlExcel8 = 56 is the .xls format
xlExcel12 = 50 is the .xlsb format
xlOpenXMLWorkbook = 51 is the .xlsx format
xlOpenXMLWorkbookMacroEnabled = 52 is the .xlsm format
xlWorkbookDefault is also listed with a value of 51, which puzzles me since I thought the default format could be changed.
I successfully use the following method in one file,
But come up with exactly the same error again...
Only the last line come up with error
Newpath = Mid(ThisWorkbook.FullName, 1, _
Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & "ABC - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
ThisWorkbook.SaveAs (Newpath)
I was struggling, but the below worked for me finally!
Dim WB As Workbook
Set WB = Workbooks.Open("\\users\path\Desktop\test.xlsx")
WB.SaveAs fileName:="\\users\path\Desktop\test.xls", _
FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
Dim NuevoLibro As Workbook
Dim NombreLibro As String
NombreLibro = "LibroPrueba"
'---Creamos nuevo libro y lo guardamos
Set NuevoLibro = Workbooks.Add
With NuevoLibro
.SaveAs Filename:=NuevaRuta & NombreLibro, FileFormat:=52
End With
'*****************************
'valores para FileFormat
'.xlsx = 51 '(52 for Mac)
'.xlsm = 52 '(53 for Mac)
'.xlsb = 50 '(51 for Mac)
'.xls = 56 '(57 for Mac)
'*****************************
When working with large amount of data where .xlsx workbook is needed, use the following syntax
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=51
(For more FileFormats see documentation.)
I think your issue was that when you use Now(), the output will be "6/20/2014"... This an issue for a file name as it has "/" in it. As you may know, you cannot use certain symbols in a file name.

Resources