vbs save and close powerpoint presentation - vbscript

I am trying to save, then close all microsoft applications, such as word, excel, and powerpoint using VBScript.
I have got word and excel to work:
'Word
On Error Resume Next
Set wd = GetObject(, "Word.Application")
On Error Goto 0
If Not IsEmpty(wd) Then
For Each doc In wd.Documents
doc.Save
doc.Close
Next
wd.Quit
End If
And:
'Excel
On Error Resume Next
Set xl = GetObject(, "Excel.Application")
If Err Then
If Err.Number = 429 Then
WScript.Quit 0
Else
CreateObject("WScript.Shell").LogEvent 1, Err.Description & _
" (0x" & Hex(Err.Number) & ")"
WScript.Quit 1
End If
End If
On Error Goto 0
xl.DisplayAlerts = False
For Each wb In xl.Workbooks
wb.Save
wb.Close False
Next
xl.Quit
Set xl = Nothing
Sadly, I have not figured out how to do the same thing with powerpoint. I have researched online, but have not found the answer. Everything I found that worked wasn't using VBScript.
This is the script that I am trying to make work:
'PowerPoint
On Error Resume Next
Set objPPT = GetObject("PowerPoint.Application")
On Error Goto 0
If Not IsEmpty(objPPT) Then
For Each doc In objPPT.Presentation
objPresentation.Save
objPresentation.Close
objPPT.Quit
Next
objPPT.Quit
End If
When I run this script, nothing happens.
Could anyone help me to fix my script please?
Thank you!
I would appreciate the time and effort spent!

This snippet should get that done by looping through the presentations collection (tested with office 2010):
On Error Resume Next
Set objPPT = GetObject(,"powerpoint.Application")
On Error Goto 0
If Not IsEmpty(objPPT) Then
For Each doc In objPPT.Presentations
doc.Save
doc.Close
Next
objPPT.Quit
End If

Note that VBA <> VBScript. Might want to change the tag to correct that.
Anyhow, you've got the object hierarchy wrong
objPPT is a PowerPoint Application object.
The Application object has a Presentations collection, containing one Presentation object for each open Presentation.
You want to iterate through the Presentations collection.
Try this. I'm guessing at the VBScript syntax from the surface of my VBA brain:
On Error Resume Next
Set objPPT = GetObject("PowerPoint.Application")
On Error Goto 0
If Not IsEmpty(objPPT) Then
For Each Presentation In objPPT.Presentations
Presentation.Save
Presentation.Close
objPPT.Quit
Next
objPPT.Quit
End If

Related

How to get reference for not built-in Object (API)

I am wondering is there a way to handle the whole process with VBscript? I have an M-Files and in VBA I am able to select the reference
After that I can use M-Files API commands to execute the code.
Dim oVaultConnections As MFilesAPI.VaultConnections
Dim oDocumentCollectionOVAP As New MFilesAPI.ObjectVersionAndProperties
Dim oOldDocumentOVAP As New MFilesAPI.ObjectVersionAndProperties
Dim oMFClientApp As New MFilesAPI.MFilesClientApplication
On Error Resume Next
Set oVault = oMFClientApp.BindToVault(szVaultName, 0, True, True)
If Err.Number <> 0 Then
' Error
Err.Number = 0
Set oVault = oMFClientApp.BindToVault(oMFClientApp.GetVaultConnectionsWithGUID(szVaultGUID).Item(1).Name, 0, True, True)
If Err.Number <> 0 Then
MsgBox "Can't connect to M-Files"
End
End If
End If
On Error GoTo 0
On Error GoTo ErrorHandler1
What about VBScript? What if I would like to create VBS file and perform all the actions with VBScript without need of VBA (for Example Excel file)?
In VBScript I have to get all objects by something like:
Set MFiles = CreateObject("Scripting.MFiles")
Is it possible somehow to get it by location of dll? What if my version will change from 19.9.8227.13? Path will be different?

returning error code to VBScript

Here is what I am trying to do:
Get a VBScript to run another VBScript.
get the second VBScript to post an error on completion, either 0 if successful or >0 if not back to the original script and then work on conditions Based on the error code returned.
Uninstall 2010 & copy office 2013
'Copy files from a network share to machine
Set FSO = CreateObject("Scripting.FileSystemObject")
WScript.Echo "Starting to uninstall Microsoft Office 2010 from the machine"
FSO.CopyFile "\\data01\Tools\WSM\Copy_2013.vbs", "C:\temp\Copy_2013.vbs"
FSO.CopyFile "\\data01\Tools\WSM\OffScrub10.vbs", "C:\Temp\OffScrub10.vbs"
FSO.CopyFile "\\data01\Tools\WSM\DeleteOffice13Package.vbs", "C:\temp\DeleteOffice13Package.vbs"
'Wait to execute rest of script where copied filed need to be in location
WScript.Sleep 5000
'Executes Office 2013 copy at the same time, do not wait to continue uninstalling office 2010
Set objShell = WScript.CreateObject("WScript.Shell")
Call objShell.Run("C:\temp\Copy_2013.vbs", 0, False)
WScript.Sleep 3000
'Run VBScript that uninstalls office 2010 (currently set to copy a non existent path for error capture test)
strRemoveOffice10 = "c:\Temp\offscrub10.vbs ALL /Quiet /NoCancel"
Call objShell.Run(strRemoveOffice10, 0, True)
WScript.Echo Err.Number
If Err.Number <> 0 Then WScript.Echo " Microsoft Office 2010 could not be uninstalled. Please uninstall again manually."
If Err.Number = 0 Then WScript.Echo "Microsoft Office 2010 has uninstalled from the machine"
Set objFileSys = Nothing
WScript.Quit
OffScrub10.vbs
Dim objFileSys
Set objFileSys = CreateObject("Scripting.FileSystemObject")
objFileSys.GetFolder("C:\Temp\Temp1\bla").Copy "C:\WSM\Test"
On Error Resume Next
If Err.Number <> 0 WScript.Quit Err
To enable error handling you need to put On Error Resume Next before the statement that may cause an error. Then you can return a status code like this:
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
fso.GetFolder("C:\Temp\Temp1\bla").Copy "C:\WSM\Test"
WScript.Quit Err.Number
However, since you said you want a return value >0 in case of an error and Err.Number is an unsigned integer that might be interpreted as a positive or negative value depending on its actual value, something like this might be a better choice:
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
fso.GetFolder("C:\Temp\Temp1\bla").Copy "C:\WSM\Test"
If Err Then WScript.Quit 1
WScript.Quit 0 'can be omitted, because it's the default
To check the returned value in the calling script you need to capture it in a variable. When using the Call statement like you do in your first script the return value is simply discarded. VBScript does not put return values of external commands in the Err object. You may also want to make sure that your script is being run with cscript.exe to avoid messages/popups blocking execution.
strRemoveOffice10 = "cscript.exe c:\Temp\offscrub10.vbs ALL /Quiet /NoCancel"
rc = objShell.Run(strRemoveOffice10, 0, True)
If rc = 0 Then
'OK
Else
'an error occurred
End If
Yes, you can return an exit code from your second script to the first as follows...
WScript.Quit(-1)
Where -1 is your exit code of choice.
Option Explicit
If WScript.Arguments.Count = 0 Then
' If we don't have any arguments, call ourselves to retrieve
' the exit code. It will be returned by the call to the
' Run method
Dim returnCode
returnCode = WScript.CreateObject("WScript.Shell").Run ( _
Chr(34) & WScript.ScriptFullName & Chr(34) & " myArgument " _
, 0 _
, True _
)
' Note ^ the "True"
' We need to wait for the "subprocess" to end to retrieve the exit code
Call WScript.Echo(CStr( returnCode ))
Else
' We have arguments, leave current process with exit code
Call WScript.Quit( 1234 )
End If
Quick sample for testing.
There are two elements to consider:
The called subprocess uses the WScript.Quit method to return the process exit code to the caller
The caller must wait for the subprocess to end to retrieve the exit code. The Run method will return the exit code of the subprocess

Loop all the rows of a worksheet and copy them into a blank sheet

I'm facing a serious problem while importing my script into UFT for more than 2 weeks, I tried everything. As a worarround, I'm cpying the workbook and then I import the new on but this sometimes doesn't work too.
this is my code:
DataTable.ImportSheet workbook1,"name1","sheet1"
this is my workarround:
On error resume next
DataTable.ImportSheet workbook_path,"name1","sheet1"
MsgBox "Error: " & Err.Number & " (" & Err.Source & ") - " & Err.Description
If Err.Number <> 0 Then
If err.number = 20012 Then
Set objExcel1 = CreateObject("Excel.Application")
objExcel1.Visible = False
objExcel1.DisplayAlerts=False
Dim RelativePath
RelativePath = "C:\xyz\new_workbook.xls"
Dim objSheet1
Set objWorkbook1= objExcel1.Workbooks.Open("workbook.xls")
Set filesys = CreateObject("Scripting.FileSystemObject")
If filesys.FileExists(RelativePath) Then
filesys.DeleteFile RelativePath
End If
Set objWorkbook2=objExcel1.Workbooks.Add
objWorkbook2.saveAs RelativePath
For each objsheet1 in objworkbook1
objworkbook2.AddSheet objsheet1.Name
objsheet1.copy objworkbook2.sheets(1)
Next
objWorkbook2.save
objworkbook1.close
objworkbook2.close
objExcel1.Quit
Set objSheet1 = Nothing
Set objWorkbook1 = Nothing
Set objWorkbook2 = Nothing
Set objExcel1 = Nothing
On error resume next
DataTable.ImportSheet RelativePath,"name1","sheet1"
MsgBox "Error: " & Err.Number & " (" & Err.Source & ") - " & Err.Description
End if
End If
I want to try looping all the rows of the sheets and copying them into the new ones instead of copying them directly. Any help please ? if anyone has other solution to solve this issue, pleeeeeeease help
Why loop through the rows if you want them all? Just copy the sheet. IF you need the code for that, fire up the macro recorder, copy the sheet and stop the macro recorder.
Change your DataTable.ImportSheet workbook1,"name1","sheet1" call to DataTable.ImportSheet workbook1,"name1","Action1" or to DataTable.ImportSheet workbook1,"name1","Global". Make sure that your path is correct for the workbook and name1 sheet exists in your workbook
Are you able to import manually into DataTable? Sometimes, the special characters from the spreadsheet throw error.
If you are receiving "Invalid file error", follow the steps.
1. Open UFT and Activate Data Table and Perform the below action
Perform
Choose the appropriate sheet to be imported.
Check if any "Invalid File Error Dialog". If yes Goto Step 5 else GoTo Step 2
Go back to actual spreadsheet and replace all of the special characters including spaces and clear all the Formatting of the cells

vbscript syntax error saving a excel file

I have my code in vb script. result of a stored procedure is saved in an excel.I'm getting error in line saying
TITLE: ActiveX Script Task
Error Code: 0
Error Source= Microsoft VBScript compilation error
Error Description: Syntax error
Error on Line 97
-----------------this is the code pls help..
Dim oFSOExcelFile
Set oFSOExcelFile= CreateObject("Scripting.FileSystemObject")
Dim workSheet,sFileName
Dim iRow,headingRow
'Create the Excel workbook
On error Resume Next
Set oXLIDRenewal = CreateObject("Excel.Application")
oXLIDRenewal.Visible=True
With oXLIDRenewal
'Make sure there is no minimized window.
.Application.Visible = False
.Application.DisplayAlerts = False
End With
If not rstRev.EOF then
'Name of the excel File to import to.
sFileName=''D:\packages\Rev&CPExcel\Rev'' &iday &''-''&imonth ''-''&iyear &''.xls''
'Delete the Excel File if it already exists.
If oFSOExcelFile.FileExists(sFileName) Then
On Error Resume Next
oFSOExcelFile.DeleteFile(sFileName)
End If
Your
sFileName=''D:\packages\Rev&CPExcel\Rev'' &iday &''-''&imonth ''-''&iyear &''.xls''
uses the wrong quotes and lacks at least one &. So try:
sFileName = "D:\packages\Rev&CPExcel\Rev" & iday & "-" & imonth & "-" & iyear & ".xls"
Double check ..\Rev&CPExcel\..

Why does my VBA script not continue after debugging?

Whenever I hit an error with my script, the focus turns to the VBA code and the offending line. I fix it, and hit save. Then I notice that the script is no longer running, even after I make sure that it's not paused.
For example, right now I'm using a Form_Timer() event to do some testing (interval set to 1000ms). To test the script again, I just set it to a minute in the future (e.g. if the current time is 8:54:00 AM I set it to fire at 8:55:00 AM). But this stops working after an error. Does anyone know why this is? I don't want to have to tell my users to close and re-open their copies of the Access DB just to make the script work again.
Code:
Private Sub Form_Timer()
On Error GoTo ErrorHandler
current_date_time = Now
If current_date_time = #6/28/2016 8:52:00 AM# Then
MsgBox ("the current_date_time variable holds: " & current_date_time)
'Declare objects
Dim dbs As DAO.Database
Dim rst As DAO.Recordset
Dim qdf As DAO.QueryDef
Dim oApp As Outlook.Application
Dim oMail As Outlook.MailItem
Dim mail_body As String
'Set objects
Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("qry_BMBFLoc")
Set rst = qdf.OpenRecordset
Set oApp = New Outlook.Application
Set oMail = oApp.CreateItem(olMailItem)
mail_body = "The following jobs do not have the special BF location set in Job Orders: " & vbCrLf
If Not (rst.EOF And rst.BOF) Then
rst.MoveFirst
Do Until rst.EOF = True
mail_body = mail_body & rst!job & "-" & rst!suffix & vbCrLf
rst.MoveNext
Loop
'Email contents
oMail.Body = mail_body
oMail.Subject = "Blah"
oMail.To = "someone#something.com"
oMail.Send
'Close stuff
rst.Close
dbs.Close
Set rst = Nothing
Set oMail = Nothing
Set oApp = Nothing
End If
End If
Exit Sub
ErrorHandler:
Dim msg As String
If Err.Number <> 0 Then
msg = "email Form Timer Error #" & Str(Err.Number) & " error Line: " & Erl & Chr(13) & Err.Description
MsgBox msg, , "Error", Err.HelpFile, Err.HelpContext
End If
Exit Sub
End Sub
In order to reactivate the code, you could close the form when the error is triggered. The user would then have to reload the form to complete the action.
However, without any intervention the error is likely to occur again.
Edit: Or you could write a Function to automatically close, and re-open the offending form. Calling it in the on error command.
When there is an error in access form, the timer will stop working, you don't need to close and reopen the whole database, only the form to start the timer again. Otherwise you can add a button called "refresh" and bind macro to it which will turn the timer on again.
Yeah this sucks. I am writing a vba script for outlook and so the only way to debug is to close and reopen outlook after every error.

Resources