Not able to save to a created folder (applescript) - scripting

so I have been trying to create a script that will create a folder on my desktop, then create a spreadsheet, and save the spreadsheet to said folder. here is the script...
set folderName to "Tester"
set FileName to "MayDay"
set SaveName to FileName & ".numbers" as string
set FilePath to "Macintosh HD:Users:Ryan:Desktop:" & FileName & ":"
tell application "Finder" to make new folder at desktop with properties {name:folderName}
tell application "Numbers" to activate
tell application "Numbers" to make new document with properties {name:FileName}
tell application "Numbers"
tell document 1
tell table 1 of sheet 1
merge range "B8:C8"
end tell
end tell
delay 1
tell application "Numbers" to activate
end tell
tell application "Numbers" to (save document 1) in FilePath
end
It has no problem making the folder, opening the spreadsheet, changing its name, and merging the cells, the problem comes in at the end when I try to save it.
I have tried adding (as numbers) no parenthesis after the save command, that errors out. After I run the script, and clear the crash, I can close out numbers and it will prompt me to save it in the "Tester" folder, but it won't do it on its own. insert grey hairs and headaches here.
I am really new to applescript, and I am hoping this is just a simple syntax thing, any help would be appreciated.
Thanks in advance!
R

Here's working code. A key is to use POSIX path and POSIX file and also the "save ... in ..." takes a file reference, not a string.
set folderName to "Tester"
set fileName to "MayDay.numbers"
set FilePath to (path to desktop as string) & folderName & ":" & fileName
set posixPath to POSIX path of FilePath
try
tell application "Finder" to make new folder at desktop with properties {name:folderName}
on error errMsg
end try
tell application "Numbers"
set myDoc to make new document with properties {name:fileName}
tell myDoc
tell table 1 of sheet 1
merge range "B8:C8"
end tell
end tell
delay 1
save myDoc in POSIX file posixPath
end tell

Related

Trying to print new folder names to a text edit/numbers file when logged (AppleScript)

I'm trying to add new folders added to a drive onto a textEdit or numbers file so that there's an up to date list of what projects I have active on individual drives.
I'm very new to AppleScript so I don't know what my limitations are, but I basically just need to figure out how to append to the end of the file (it seems like textEdit would be simplest) with the name of the new folder. I currently have:
on adding folder items to theAttachedFolder after receiving theNewItems
-- Get the name of the attached folder
tell application "Finder"
set theName to name of theAttachedFolder
-- Count the new items
set theCount to length of theNewItems
-- Display an alert indicating that the new items were received
activate
display alert "Attention!" message (theCount & " new items were detected in folder. Adding to TextEdit file.")
end repeat
end tell
Any help is much appreciated. Thank you!
The File Read/Write suite in the StandardAdditions scripting dictionary has open for access and write commands that can be used to append to a text file (the AppleScript Language Guide also has a command reference), and AppleScript's text item delimiters or string concatenation can be used to assemble a string from the list of file items.
There are some older topics describing ways to write to a file, but in the following example I've separated the main stuff from the folder action handler so that it can also be called from the run handler for testing in the Script Editor:
property logFile : "/path/to/output/textfile.txt" -- HFS or POSIX
on run -- test
set folderItems to (choose file with multiple selections allowed)
tell application "Finder" to set theFolder to container of first item of folderItems
doStuff(theFolder, folderItems)
end run
on adding folder items to theAttachedFolder after receiving theNewItems
doStuff(theAttachedFolder, theNewItems)
end adding folder items to
to doStuff(theFolder, theItems)
set folderItems to ""
activate
display alert "Attention!" message "" & (count theItems) & " new items were detected in folder." & return & "Adding to log file."
tell application "Finder" to set folderName to name of theFolder
repeat with anItem in theItems
tell application "Finder" to set newName to name of anItem
set folderItems to folderItems & tab & newName & return
end repeat
writeToFile(logFile, "Items added to " & folderName & ":" & return & folderItems & return)
end doStuff
to writeToFile(someFile, someText)
try
set theOpenFile to (open for access someFile with write permission)
write someText to theOpenFile starting at eof -- append
close access theOpenFile
on error -- make sure file is closed
try
close access theOpenFile
end try
end try
end writeToFile

Merge pdf files with VBA and Foxit

I use Foxit Phantompdf, the complete version and ACCESS.
In our program, we have to save multiple pdf files, some of them should be merged in single files when saved.
Here is the code I use;
Dim phApp As PhantomPDF.Application
Dim n1 As String
Dim n2 As String
n1 = "c:\Temp\F3769-190136-GROUPE OCÉAN.pdf"
n2 = "c:\Temp\f3769-190136-GROUPE OCÉAN- facture.pdf"
Set phApp = CreateObject("PhantomPDF.Application")
Dim phCreator As PhantomPDF.Creator
Set phCreator = phApp.Creator
***'Call phCreator.CombineFiles("c:\Temp\F3769-190136-GROUPE OCÉAN.pdf|c:\Temp\f3769-190136-GROUPE OCÉAN- facture.pdf", "c:\Temp\F3769-190136-GROUPE OCÉAN.pdf", COMBINE_ADD_CONTENTS)***
Call phCreator.CombineFiles("""c:\Temp\" & n1 & "|'" & n2 & """" & ", " & """c:\Temp\F3769-190136-GROUPE OCÉAN.pdf"""" &", COMBINE_ADD_CONTENTS)
phApp.Exit
When I try it with the complete files names (in bold) the code works perfectly.
However, when I try to use variables, I get a
"Argument not optional"
error.
Can somebody help me ?
Thanks
Your string definitions in call line is incorrect.
You have defined n1 and n2 with the c:\temp already, and in your string conversion you add this again. I do not know if this is the route cause to your issue.
Furthermore I do not know the actual needed syntax for this phcreator.combine()
But is it not possible using only:
call pHcreator.combine(n1 & "|" & n2, …
The 'Argument not option' might imply you should add another input to your pHcreator, I would guess it could have something to do with FOXIT's combine function page settings. Try adding a input variable integer at the end of the function maybe?
But the fact that it works when writing strings in clear text would maybe suggest that the string manipulations is not correct?
I'm not a vba professional, but interested in the outcome, working myself with Foxit and also want to combine with vba. I'm currently not using version 9 som I seem to be out of luck, and only upgrading it I know what I want to do is possible.
I tried it, but got the same error message. So I took advantage of the fact that the function works when the file names are in plain text. I copied the files to be merged in a temporary folder and rename them. The renamed files are the then used in the merge function. It works perfectly, but Foxit adds a table of content page, and I don't know, yet, how to remove it. Here is my solution:
Private Sub Command4_Click()
Dim addi As String 'file to be merged to main file
Dim princi As String 'main file
Dim phApp As PhantomPDF.Application
'A temporary folder, in this case c:\t2, should be present
'In this example c:\Temp is the working folder
addi = "c:\Temp\filetomerge.pdf" 'full path of file to be merged
princi = "c:\Temp\mainfile.pdf" 'full path of main file
'fadd,pdf and fmain.pdf are the temporay files used in Foxit's function
FileCopy addi, "c:\t2\fadd.pdf" 'temporary file to be merged in temporary folder
FileCopy princi, "c:\t2\fmain.pdf" 'temporary main file in temporary folder
'Merge action
Set phApp = CreateObject("PhantomPDF.Application")
Dim phCreator As PhantomPDF.Creator
Set phCreator = phApp.Creator
Call phCreator.CombineFiles("c:\t2\fmain.pdf|c:\t2\fadd.pdf", "c:\t2\fmain.pdf", COMBINE_ADD_CONTENTS)
phApp.Exit
'Save merged file in working folder under main file name
Kill princi
FileCopy "c:\t2\fmain.pdf", princi
'delete temporary files
Kill "c:\t2\fadd.pdf"
Kill "c:\t2\fmain.pdf"
End Sub

Random File Selector?

It's been years since I've used Visual Basic. I downgraded from 2017 to 2010 (The version I was using while I was in school). I figured VB would be the best way to attempt a solution. (Although I'm sure there are other languages that would do it as well.)
I'm looking to get back into programming. Let me get to the problem.
My friend has an ever growing amount of text documents in a folder, and he wants a program to choose one at random, and open it.
I thought I'd put a TextBox with a Button that would let him open the folder where he stores his files. Then this program would read the number of text files in that folder, and randomly generate a number between one and that number, select, and open the document with its default program (if it's text, notepad; if it's DocX then word.)
I've been sitting at a blinking cursor for 45 minutes. I've gone on YouTube for help with this project.
Any advice, or help you guys can give me? Does this need to be simplified?
That sounds like a reasonable strategy to me.
It might be worth displaying some sort of progress to the user, say by putting the name of current file name being read into the status bar, in case there's a long delay reading the file names due to the large number of files in the folder, and/or a slow-running network drive. If you do this, remember to put a DoEvents into your loop to allow screen updates to display.
There's a separate thread on how to open files in their native handler here.
Hope this helps - good luck!
Option Explicit
Public oFSO As Object
Public arrFiles()
Public lngFiles As Long
Sub Main()
Dim sPath As String
sPath = InputBox("Enter folder path", "Folder path")
' clear starting point
lngFiles = 0
Erase arrFiles
Set oFSO = CreateObject("Scripting.FileSystemObject")
Call recurse(sPath)
Randomize
Dim lngRandomFileNumber As Long
lngRandomFileNumber = CLng(lngFiles * Rnd) + 1
MsgBox "This is random file, that will be opened: " & arrFiles(lngRandomFileNumber)
Call CreateObject("Shell.Application").Open(arrFiles(lngRandomFileNumber))
End Sub
Sub recurse(sPath As String)
Dim oFolder As Object
Dim oSubFolder As Object
Dim oFile As Object
Set oFolder = oFSO.GetFolder(sPath)
'Collect file information
For Each oFile In oFolder.Files
lngFiles = lngFiles + 1
ReDim Preserve arrFiles(lngFiles + 1)
arrFiles(lngFiles) = sPath & "\" & oFile.Name
Next oFile
'looking for all subfolders
For Each oSubFolder In oFolder.SubFolders
'recursive call
Call recurse(oSubFolder.path)
Next oSubFolder
End Sub
You can paste this code in any VBA supporting application (MS Access, MS Excel, MS Word), call VBA editor (Shift + F11) and paste this code. After that press F5 and select Main() function. You'll see prompt to enter folder path, and after that you would get random file path.
I think it should be understandable in practice to see what program do
Updated: #Belladonna mentioned it clearly, to open file in default program.
NB: This code is passes through subfolders also, if you want to exclude subfolders, you should comment the recursive call block in recurce function

Kill Command Deleting Wrong File(s)i

In Access VBA, I have a procedure I've put together to do this:
Allow the user to select zip file(s)
Extract any files from the zip files to the same directory (In this
specific use-case instance, it is ALWAYS extracting Excel files from
Zip files, never any change, and always using the same password)
Then I want the code to Delete the Zip file after extracting the
.xls file.
Everything works beautifully except the delete file portion. The issue is that when I tell it to delete "FileName.Zip", it is deleting "FileName.Zip" AND "FileName.xls"
Is there any way to make sure that he kill command ONLY deletes what I want it to delete? I've used it before on various occasions, and never had this happen before.
Here is the code I am using:
Dim fd As FileDialog
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim i As Variant
Set db = CurrentDb
Set rs = db.OpenRecordset("tblProjectPath")
Set fd = FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = True
fd.Title = "Select TOC Return File(s) to process"
fd.InitialFileName = rs.Fields("ProjectPath") & "\FilingReports\*.zip"
fd.Show
For Each i In fd.SelectedItems
'Debug.Print i
Debug.Print '------------------------'
Debug.Print i
Unzip (i) 'The bit calling the command line unzip utility to unzip the file - just telling it to extract all files to the current folder.
Debug.Print i
'Kill i
'had to take out the kill bit, b/c it was deleting both the .zip and .xls files which is not desired nor expected
If InStr(i, ".zip") Then
Kill i 'Tried to specify only .zip files even though think I shouldn't need to, but it's still deleting .xls files
End If
Next i
Edit: Add Unzip code to post:
Unzip code:
Sub Unzip(Path As String)
Dim strUnzip As String
Dim QU As String 'quotation mark
QU = Chr(34)
strUnzip = QU & "c:\program files (x86)\winzip\wzunzip" & QU & " -s" & _
"ZipPassword " & _
Path & " " '& _
Call Shell(strUnzip)
End Sub
At this point, I don't really think a "real" answer will come about. However, I'll post what I've decided to do with the particular process I'm writing this code for anyway.
I'm going to use a folder structure to divide up the files:
1. Place zip file(s)
2. Unzip files to a 2nd folder
3. After processing Excel files in 2nd folder, move to a 3rd "complete" folder.
This will get around the deleting wrong files bit.
Also, it appears that the cause for the issue is related to something to do with the call to the WinZip Command Line Unzip utility (wzunzip) in the Unzip code above, or else something with the tool itself. I thought that maybe it was b/c the tool was asking me if I wanted to overwrite existing files, but that wasn't the case, b/c I had the same issue when there were no files to overwrite.
Anyway, I'm attempting to close this one up at this point. Thanks to Wayne G. Dunn for his assistance on this.

How can I create a display dialog that presents specific file path options for a given PDF file?

I am very new to using Automator and Applescript.
I would like to use Automator and AppleScript to detect PDF files that are downloaded to the "Downloads" folder and opens a display dialog that allows me to select the file path and move the file. So far, what I have (which isn't right) is something like:
set question to display dialog "Save fileName in..." buttons {"Figuring Relation", "Iconoclasm", "Elsewhere"} default button 3
set answer to button returned of question
if answer is equal to "Figuring Relation" then
tell application "Finder" to move fileName to POSIX file "/Users/mac/Documents/College/Junior/Fall/Art 347 - Figuring Relation"
I want the "Figuring Relation" and "Iconoclasm" buttons to change the file path to a designated file path (I don't want to browse for it), and the "Elsewhere" button to open a Finder window where I can select/browse the path.
If possible, I'm also looking to add the date to the beginning of the file name as "mm-dd_filename".
I am not sure of how to translate the Automator Input to Applescript, or how to include the filename in the display dialog text. Thank you so much for any help.
Here is an example using just applescript. In my example, it assumes you're selecting the file you're wanting to move, but you could easily add something for the script to "Find" all files ending with ".pdf" if you wanted to and then loop through the results.
on run
try
set thisFile to choose file
tell application "Finder" to set currentName to thisFile's name
-- Setting variables for the destinations to be used later
set FiguringRelationPath to (path to documents folder) & "College:Junior:Fall:Art 347 - Figuring Relation:" as string
set IconoclasmPath to (path to documents folder) & "Iconoclasm:" as string
-- Ask the user
set answer to button returned of (display dialog "Save \"" & currentName & "\" in..." buttons {"Figuring Relation", "Iconoclasm", "Elsewhere"} default button 3)
-- Set the destination variable based on the users response to the dialog
if answer is equal to "Figuring Relation" then
set destination to FiguringRelationPath
else if answer is equal to "Iconoclasm" then
set destination to IconoclasmPath
else
set destination to choose folder with prompt "Please select the destination folder" as string
end if
-- Test that the destination directory exists, if not post the error
try
set destination to destination as alias
on error
error ("Destination path " & destination as string) & " doesn't appear to exist"
end try
-- Rename the file with the date prefix
set tDatePrefix to (do shell script "date '+%m-%d'") & "_" as string
tell application "Finder" to set x's name to tDatePrefix & x's name as string
-- Move the file
tell application "Finder" to move thisFile to destination
on error err
activate
display dialog "Error: " & err buttons {"OK"} default button 1
end try
end run