How to open a file and make it default in VBA - vba

I am trying to make "python.py" to open in notepad each time...I have got the code that does that but how to make it as default..so next time if the user wants to open the python file in notepad, it should open in notepad all the time using VBA and only after the code is excecuted...please find the code below for opening a python file in notepad..
Shell "notepad C:\Users\stackoverflow\Desktop\python.py", vbNormalFocus

You could try a VBA macro attached to a button that does this. But I am unsure if this is what you are asking for.
Sub LetterChecklist()
Dim strPath As String
Dim strProgram As String
strPath = "\\aw\data\Letters\2099_Correspondence\Incoming Letters\.pdf"
strProgram = "C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe"
Call Shell("""" & strProgram & """ """ & strPath & """", vbNormalFocus)
End Sub

Related

Filesystemobject Textstream, immediately disappears upon executing Textstream.Close (.vbs extension being created)

I have a situation that is really flummoxing me. Simple code I've used for years is failing in the weirdest way. I have a feeling the cause is related to either anti-virus junk or GPO, but, even those, I have seen them operate before on this scenario--but nothing like how I am seeing it now.
Note - this code has been working perfectly for several people, until one end-user got a new Surface laptop from I.T., purportedly for better compatibility with Teams and 365. ALL users (working, non-working) are on Windows 10.
Scenario:
I'm using Scripting.Filesystemobject
setting an object variable (Textstream intent), as fso.createtextfile
The filepath (name) I am creating is actually filename.vbs...At the moment this line executes, I can see the vbs file successfully in the folder
I use Textstream.Write to put some content in the file
I then use Textstream.Close (normally at this point you get a solid, stable, useable file). Immediately upon execution of the last line, Textstream.Close, the file DISAPPEARS from the folder-GONE.
The folder I'm writing to is the same as Start > Run > %appdata%
I've also tried this in Documents folder (Environ$("USERPROFILE") & "\My Documents") and get the exact same result
I've seen group policies and AV stuff that will prevent VBS from running, but that isn't my case--I've tested with this user, and she has no problem:
Creating a txt file in either of those folders
Manually creating a .vbs file in either of those folders
Even RUNNING the resulting vbs file in either folder
But somehow when I programmatically create .VBS in code, the second I close the textstream, the file is gone from the folder.
Any insight? The internet searches I did were void of all information on this scenario!! It would take me 2 weeks to open a ticket and get any help from I.T.
This is Excel VBA, but I highly doubt the problem has anything to do with Excel nor VBA...this is standard usage of windows scripting.filesystemobject:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
'initiate full backup vbs script:
Dim ts As Object, fso As Object, strScriptText As String, strScriptPath As String
'populate our variable with the full text of the script: found on QLoader in this range:
strScriptText = ThisWorkbook.Worksheets("QLoader").Range("z_BackupScriptText").Value
'replace the text "placeholder" with this workbook's actual full path/name:
strScriptText = Replace(strScriptText, "placeholder", ThisWorkbook.FullName)
'fire up FSO:
Set fso = CreateObject("scripting.filesystemobject")
'determine the new VBS file's path
strScriptPath = Environ("AppData") & "\Backup_" & Format(Now, "yymmddhhmmss") & ".vbs"
'create our textstream object:
Set ts = fso.createtextfile(strScriptPath)
'write our script into it
ts.write strScriptText
'save and close it
ts.Close 'RIGHT HERE THE FILE DISAPPEARS FROM THE FOLDER ***********
'GO:
Shell "wscript " & strScriptPath, vbNormalFocus
End Sub
It does look like an antivirus thing...
If the issue is just the vbs extension though, you can use something like this:
Sub tester()
Dim ts As Object, fso As Object, strScriptText As String, strScriptPath As String
Set fso = CreateObject("scripting.filesystemobject")
strScriptPath = Environ("AppData") & "\Backup_" & Format(Now, "yymmddhhmmss") & ".txt"
Set ts = fso.createtextfile(strScriptPath)
ts.write "Msgbox ""Hello"""
ts.Close
'need to specify the script engine to use
Shell "wscript.exe /E:vbscript """ & strScriptPath & """ ", vbNormalFocus
End Sub

Print File - Macro

I have created a macro that I can use to print PDF files. The PDF files will be saved in a folder to print. The path will be given that folder path where I save all PDF files. My questions are:
1) Once the files are saved in folder, is it possible to sort it automatically like first come first print. Now the issue is - prints did not come out in order of how the files are – we have to reconcile all files, so looking for each one in a random list order would take lots of time.
2) Is it possible to have the files automatically deleted from the folder after the printing is completed?
Public Sub Print_All_PDF_Files_in_Folder()
Dim folder As String
Dim PDFfilename As String
folder = "\\maple.fg.rbc.com\data\toronto\user_3\315606053\myWorkspace\Desktop\test" 'CHANGE AS REQUIRED
If Right(folder, 1) <> "\" Then folder = folder & "\"
PDFfilename = Dir(folder & "*.pdf", vbNormal)
While Len(PDFfilename) <> 0
If Not PDFfilename Like "*ecg*" Then
Print_PDF folder & PDFfilename
End If
PDFfilename = Dir() ' Get next matching file
Wend
End Sub
Sub Print_PDF(sPDFfile As String)
Shell "C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe /p /h " & Chr(34) & sPDFfile & Chr(34), vbNormalFocus
' This is path of Adobe in the desktop
End Sub
There is no build in way to sort files. However, it is rather easy to read the filenames and -dates into arrays and sort them manually, but you have to use the FilesystemObject rather than using dir to get the file dates.
You can find an example to do so for example here: https://social.msdn.microsoft.com/Forums/office/en-US/5f27936e-1d98-44df-8f69-0f81624c4b92/read-files-in-a-folder-in-descending-order-with-file-name-or-date-created?forum=accessdev
The command to delete a file with VBA is kill, or you can use the .DeleteFile method of FilesystemObject. However, this will work only if the printing is already done, so you have to wait for your shell-command to finish. For this, you have to use the wscript.shell, see for example here https://stackoverflow.com/a/8906912/7599798

Saving MS word (docx) as pdf on Mac OS X with one click using macros

I have a question on how to edit the following macros to save MS word (.docx) file as PDF on macOS Sierra without .docx in the file name. That is, the macros works perfectly BUT it always saves files as, for example, letter.docx.pdf. It is a very easy option to save in pdf with one click only.
And I would appreciate if someone could help to me amend the macros below so that there is no .docx in the file name. I have tried to hide extensions in Finder, but that does not seem to help:
Sub SaveActiveDocAsPDF()
On Error Resume Next
ActiveDocument.SaveAs _
fileName:=ActiveDocument.FullName & ".pdf", _
FileFormat:=wdFormatPDF
End Sub
Thank you very much in advance.
You need to remove the existing file extension before adding the new one. Like this:
Sub SaveActiveDocAsPDF()
On Error Resume Next
Dim saveName As String
saveName = ActiveDocument.FullName
saveName = Left(saveName, Len(saveName) - 5) & ".pdf"
ActiveDocument.SaveAs fileName:=saveName, _
FileFormat:=wdFormatPDF
End Sub

VBA that runs shell command works only in debug mode

I wrote some VBA code that calls ftp.exe via shell command. When the code runs, the shell command does not execute. However, if I step through the code in debug mode, it works every time. Here is the code:
Sub FTPFile(sSrc As String)
Dim sHost As String
Dim sUser As String
Dim sPass As String
Dim sDest As String
Dim sFTPCmds As String
Dim strConnect As String
'Build up the necessary parameters
sHost = "<redacted>"
sUser = "<redacted>"
sPass = "<redacted>"
sDest = "\"
'Write the FTP commands to a text file
iFNum = FreeFile
sFTPCmds = "<path redacted>" & "FTPCmd.tmp"
Open sFTPCmds For Output As #iFNum
Print #iFNum, "op " & sHost
Print #iFNum, "user " & sUser & " " & sPass
Print #iFNum, "cd " & sDest
Print #iFNum, "put " & sSrc
Print #iFNum, "bye"
Close #iFNum
Shell Environ("WINDIR") & "\System32\ftp.exe -n -s:" & sFTPCmds
End Sub
The only possible idea I came up with is that the user permissions that call this command differ based on whether the call occurs in debug mode or running, but I am unsure how to change the command.
Perhaps I can shed some light on this. I was experiencing a similar issue where I was creating a temporary pdf file and then using a shell command and pdftk to combine the temporary pdf file with another pdf and output the result. It was working perfectly when I stepped through the code, but during runtime I wasn't getting the output. As #Smandoli mentioned above, it is likely to be a timing issue.
My code was;
Dim wsh As Object
Set wsh = CreateObject("WScript.Shell")
wsh.Run "pdftk.exe """ & pdf1 & """ """ & pdf2 & """ output """ & ActiveWorkbook.Path & "\" & outputFile & """"
After the shell command was initiated I was removing the temporary file using
Kill ActiveWorkbook.Path & "\" & pdf1
It turns out this was occurring before the shell command could execute.
Forcing the shell command to wait for return solved the issue, as shown in this post: Wait for shell command to complete. This post recommends using WSScript.Shell over Shell as it has a wait on return option.
I had a piece of VBA macro code where:
1) The macro prepares some data in the Excel spreadsheet,
2) Opens another Excel file,
3) Writes data to the opened file spreadsheet cells,
4) Saves and closes the opened file
The macro ran perfectly in the debugger.
...but not in real time from the application. It opened the other file and then stopped working. Nothing happened, the opened file was not updated nor saved and closed. Excel was not stuck.
I tried the delay loops and application.wait after a hint from a fried. No help.
But then, I found DoEvents. Voila, it solved the problem. I put DoEvents before and after the file open and now it runs perfectly!
Usually this is a timing issue and it can be difficult to trace.
See some approaches here and here.
As a first step, add the DoEvents command at different spots. This prompts Windows to work on pending tasks outside the Access process.
Adding a timed loop to stave off a time-out is sometimes the answer, even though it seems unbearably kludgey.

VBA calling vbs file form Program Files, won't call

I currently have the following code to call a vbs file that is in a folder within Program Files. It was originally in a different location (within the same folder) and it would work, but now there is a padlock symbol next to the folder within Program Files, and after changing the location (VBA updated for this as well), it won't call the file. I'm wondering why this is happening.
Sub ChangeThemeBasic()
Dim filespe As String
filespe = "cmd.exe /c C:\Program Files\Theme Changer\ChangeTheme.vbs"
X = Shell(filespe, 1)
End Sub
EDIT:
This works for some reason, I don't know why though:
Sub Test()
Shell "Explorer.exe ""C:\Program Files\Theme Changer\ChangeTheme.vbs""",1
End Sub
From comments
Sub ChangeThemeBasic()
Dim filespe As String
filespe = "cmd.exe /c " & Environ("AppData") & "\Theme Changer\ChangeTheme.vbs"
X = Shell(filespe, 1)
End Sub