Task Scheduler failed to run the Excel VBA Macro - excel

I created an Excel VBA that check for data in the cells and send email with WorkBook_Open().
Option Explicit
Private Sub Workbook_Open()
'Declaring variables
Dim notifyEmailApplication As Object
Dim notifyEmailContent As Object
Dim triggerEmailApplication As Object
Dim triggerEmailContent As Object
'Create email object
Set notifyEmailApplication = CreateObject("Outlook.Application")
Set notifyEmailContent = notifyEmailApplication.CreateItem(0)
Set triggerEmailApplication = CreateObject("Outlook.Application")
Set triggerEmailContent = triggerEmailApplication.CreateItem(0)
...
I then created a VBScript to run the Excel file.
Call ExcelMacro
Sub ExcelMacro()
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.DisplayAlerts = False
Set xlBook = xlApp.Workbooks.Open("....\Email Automation.xlsm", 0, False)
xlBook.Close
Set xlBook = Nothing
xlApp.Quit
Set xlApp = Nothing
End Sub
I also created a cmd file to run the VBScript on cscript.exe
cscript.exe "....\vbscript.vbs"
exit
Whenever I trigger the cmd file manually (double clicking it), the Excel Macro runs perfectly and successfully send email to the designated person.
But when I use Task Scheduler to run the cmd file, the Excel Macro does not run successfully and this line was highlighted.
Set notifyEmailApplication = CreateObject("Outlook.Application")
Notes: I already viewed a lot of forums and didn't find a fix:
In 'dcomcnfg' I already set Outlook Message Attachment to Interactive User
I tried changing Dim notifyEmailApplication As Object to Dim notifyEmailApplication As Outlook.Application, same line is highlighted
I already added Outlook Object Library as reference in Excel VBA

But when I use Task Scheduler to run the cmd file, the Excel Macro does not run successfully
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.
Read more about that in the Considerations for server-side Automation of Office article.
If you deal with open XML documents you may consider using the Open XML SDK instead, see Welcome to the Open XML SDK 2.5 for Office for more information. Also take a look at any third-party components designed for the server-side execution (they don't require Office installed on the system).

I haven't touched this topic for many years, but as I remember, from a long time ago, the Task Scheduler allows, or requires, you to enter your Windows password and if the password is incorrect it won't notify you of the error, so it seems like it's working, but with the incorrect password, it won't work. Can you double-check that your Windows password is entered correctly?

Related

the remote server machine is unavailable error '462'

I have an excel userform a screen shot of which I would like to include in an outlook email. It works fine on my main programming computer, but when I run the same program on other computers I get the above error. The excel workbook is in the cloud and is run from the cloud (google drive) on various computers. the code is:
Function outlookEmail()
Dim doc As Object, rng As Range
Application.SendKeys "(%{1068})"
DoEvents
'ActiveSheet.Paste
With CreateObject("Outlook.Application").CreateItem(0)
.display
Set doc = .GetInspector.WordEditor
doc.Range(0, 0).Paste
.To = sDetail.Cells(myRow, headerDict.item("email"))
.Subject = "documents for you"
End With
End Function
the error is on the set doc line, if I mark it out, the error moves the the next line: doc.range...
Outlook is a singleton. That means you can't run two instances of the application at the same time. If the Outlook Application is already running under the different security context you may get into troubles. So, I'd suggest checking whether Outlook is already running and make sure it is running under the same security context, so you could reach the instance.
You can use the Visual Basic GetObject function to return a reference to the Application object that represents a session that is already running. Note that because there can be only one instance of Outlook running at any given time, GetObject usually serves little purpose when used with Outlook. CreateObject can always be used to access the current instance of Outlook or to create a new instance if one does not exist. However, you can use error trapping with the GetObject method to determine whether Outlook is currently running.
Read more about that in the Automating Outlook from Other Office Applications article.

workbooks.add fails when vbs-script is called from Task Scheduler

I have some code in VBscript that creates an excel object and adds a workbook to it
Dim oExcel, oWB
Set oExcel = CreateObject("excel.application")
Set oWB = oExcel.Workbooks.Add()
When I run this myself (using VbsEdit or cscript), it has no issues and does the job.
When I make an entry in the Windows 10 Task-Scheduler (or Server 2019 too), run it with setting 'even if the user is offline', it fails with errorcode -2147023170. When I say the user MUST be online (useless, but I tried it anyway) then I get the error 1004 - Unknown runtime error.
I can't figure out what causes this. I presume it's a Office 365 issue, because on an older system (windows server 2012 R2 with office 2016) it runs just fine from the task scheduler.
The account it runs under is administrator, the task runs with the highest priority. The Vbs is not called directly, but using a bat-file with logging. Running a vbs-script directly from the task scheduler seems to get stuck at "running" indefinately :(
Who knows how to fix this ?
Thanks,
Paul
How about removing the brackets at the end of Workbooks.Add?
Set oWB = oExcel.Workbooks.Add

How to work around Excel 2016 halting without message when trying to assign variable to VBProject?

System Details.
Windows 10
Excel 365 64-bit V16.0 (Apps for Enterprise)
Issue.
I have a macro that opens a file, checks if the user has allowed programmatic access to the VBA Project in the trust center and raises an alert if they have not. This works fine on windows 7 machines with both 32bit and 64bit Excel from 2013 onwards.
The specific problem I am having on the Windows 10 machine is that when workbooks.open(path) is executed the file opens but in the VBA Project explorer window the VBAProject object for that file does not appear. I also get a popup saying that code cannot be run in break mode when I try this while stepping through the code. When run on Win 7 with this version of Excel and others both 32 and 64-bit the VBAProject object appears and no popup is generated.
This lack of the VBA Project causes an issue later when I run set vbproj = ActiveWorkbook.VBProject. At this point when stepping through the code execution halts with no messages at all. The Project pops up in the Project explorer window and it takes me to a module in the opened workbook. This gets opened with Design Mode turned on and when you click to turn it off I get an error message saying 'Macros have been disabled'
Notes
set vbproj = ActiveWorkbook.VBProject works fine if the file is open and the VBAProject is visible in the Project explorer window.
If the file being opened does not contain a macro then it works correctly.
I have made sure that the files are in a Trusted Location.
I have set Enable all macros in the Macro Settings of the Trust Center.
When opening the files manually I do not get any alerts that macros have been disabled by an administrator and I do not get any message asking if I want to enable macros.
I have looked at W10 group policies to see if there is one that would block VBAProjects / Macros from files opened via VBA and there does not appear to be one as far as I can see.
The Trust Center setting for programmatic access to the VBA Project does not matter to this test case. It will return True if it is allowed and False if it is not allowed.
This has been tested on another Windows 10 laptop with the same version of Excel 64-bit and it has the same result so is not an issue with a specific users laptop.
I removed the folder from the Trusted Location on the Windows 7 machine and the code still executes correctly and returns True/False.
In the actual macro this check is done for each opened file in a loop and the variant vbproj is used to remove data from the modules within that project. I have considered working around the issue by using Application.onTime and that may be a solution but have not spent much time on that and with how it halts it may not be viable.
Attempted Solutions
I have tried set wb = workbooks.open(path) to open the workbook and then using set vbproj = wb.VBProject but it has the same behavior as above.
I have tried doing ActiveWorkbook.Activate and similar actions to see if that will make the VBA project appear, it does not.
I have tried setting Application.FileValidation = msoFileValidationSkip before opening the file, this does not change the behavior.
I have tried setting Application.EnableEvents=False before opening the file, this does not change the behavior.
I have tried making vbproj a variant, an object and a VBProject, this does not change the behavior.
Steps to Recreate
Create a new workbook.
Put the below code into Module 1.
Function projectAccess()
Dim vbproj As Variant
On Error GoTo noaccess
Set vbproj = ActiveWorkbook.VBProject 'If access is denied an error is raised.
projectAccess = True
Exit Function
noaccess:
projectAccess = False
End Function
Sub openfile()
Dim filepath As String
filepath = Application.ThisWorkbook.Path
Workbooks.Open (filepath & "\openfile.xlsm")
Debug.Print projectAccess
End Sub
Save the workbook
Create a 2nd workbook, in my case it was called openfile.xlsm and put some code into Module 1.
put both workbooks in the same location and make sure it is a Trusted Location in Excel.
run openfile().
If successful the immediate window will display True / False depending on the Trust Center setting.
I am out of ideas. Any suggestions for some setting that I may have overlooked to make the Win 10 machines behave the same as the Win 7 machines or suggestions for a possible work around?
Even if it is a group policy setting that would be something I can raise with IT as long as I know what to ask for.
Many Thanks
Andrew
EDIT: Thanks to Rory in the comments the issue was making sure that the automation security was set like so Application.AutomationSecurity = msoAutomationSecurityLow as the way the new Win 10 + Office 64 systems have been set up by my IT dept is to have it default to msoAutomationForceDisable

Vbs on Excel Starter 2010: activex component can't create object Excel.Application

I have a new pc with Windows 7 and Office Starter 2010 pre-installed. If I launch the following simple vb script (from command line: cscript testScript.vbs):
Dim xlApp
Set xlApp = CreateObject("Excel.application")
xlApp.visible = True
Set xlWorkbooks = xlApp.Workbooks
Set xlWorkbook = xlWorkbooks.Open("C:\path\myFile.xls")
xlWorkbook.ActiveSheet.Rows("1:2").AutoFit
xlApp.visible = False
xlWorkbook.Save
xlWorkbook.Close("C:\path\myFile.xls")
xlApp.Quit
Set xlApp = Nothing
it returns this error: activex component can't create object 'Excel.Application'.
I don't understand if the error is due to Starter limitations (http://office.microsoft.com/en-us/starter-help/excel-features-that-are-not-fully-supported-in-excel-starter-HA010374501.aspx), and I found dissenting opinions on the web.
Is there a way to make it works using Office Starter version?
Despite this is already very aged question, I haved decided to post the following information only to help other googlers.
Since you are trying to create an instance of Excel.Application outside VBA, there's a good chance of being succeeded if you install an updated version of Microsoft Excel Viewer on target machine. This will allow you to access Excel's API.
Bear in mind, that Excel Starter Edition does not support macros, along with other important limitations.
Cheers!

Producing Excel files in ASP on IIS7.5

On an existing web application I support there is a page that is used to produce an Excel spreadsheet for some data. The Web server has Excel 2002 installed (so old...) and makes uses of automation of the Excel object to do the work.
I am fully aware that automating Excel like this is not recommended by Microsoft, but this is the way is currently works, and I am never allocated any time to look to change this.
Here is some sample code
Dim xlApp, xlBook, xlSheet
'create the Application Object and workbook object
Set xlApp = Server.CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets.Add
'turn off any alerts
xlApp.DisplayAlerts = False
xlApp.Visible = False
xlApp.ScreenUpdating = False
xlApp.DisplayFormulaBar = True
xlApp.CommandBars("Standard").Visible = True
xlApp.CommandBars("Formatting").Visible = True
xlApp.CommandBars("Chart").Visible = True
xlApp.CommandBars("Control Toolbox").Visible = True
xlSheet.Cells(1, 1).Value = "Test"
xlApp.ScreenUpdating = True
xlApp.ActiveWorkbook.SaveAs ("C:\Temp\Test.xls"), -4143
xlApp.Quit
Set xlApp = Nothing
The Web Server is a Windows 2003 server, running IIS6, and everything works happily. However, we are currently upgrading to using Windows 2008 servers, running IIS7.5 and the above code is no longer working. The message returned is as follows:
Microsoft Excel error '800a03ec'
SaveAs method of Workbook class failed
xxxxxx/Test_Excel.asp, line 42
The thing is, is that if I create a simple .vbs file, with the above code and run it, it all works as expected. It is only when running as an ASP page does it fail.
The folder is it trying to write to should have the correct permissions (I added 'Everyone' to it, with full access).
Does anyone have any suggestions as to why this is happening?
Thanks!
First of all I'd remove that Everyone group from the folder you're trying to write to, that's leaving open a potential security headache for another day.
There's a few different ways that your site could be configured to authenticate which will determine the identity that the Excel COM server will launch as.
However, rather than go through them all, create a script that does just this:
<%
Dim xlApp, xlBook, xlSheet
'create the Application Object and workbook object
Set xlApp = Server.CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets.Add
%>
Open task manager, select the "Processes" tab. Ensure that "Show processes from all users" is enabled and sort the processes by Image Name.
Browse to the script above and you should see the Excel.exe appear in the process list:
In the third column you will see the identity that Excel is running under. That's the account that needs write permissions to your c:\Temp folder.
When you do this you'll need to manually kill Excel.exe because it'll just keep running otherwise.
The only thing I can recommend is to check your App Pools in IIS7. Within the Advanced Settings of the App Pool, you may have to change the Identity account to one of the built-ins. By default in IIS7.5+, a dynamic account is used with the name of the App Pool and it appears in your Task Manager with the name.

Resources