Importing Excel files into Access with Excel 2016 - excel

We currently have Office 2010 and are moving to Office 2016. I have an Excel macro that I am try to testing. I use the following shell command to open access and run a macro to import some excel files into a database. This has worked great and never has any issues.
Shell "C:\PROGRA~1\MICROS~1\Office14\MSACCESS.EXE \\Vs300\rental_public\SHARED~1\SSDATA~2.MDB /X Upload_Manheim", vbMaximizedFocus
When I look for the Access application on my machine the path is as follows:
C:Program Files\Microsoft Office\Office14
When I search for the Access application on the test machine, the path is as follows:
C:Program Files (x86)\Microsoft Office\root\Office16
I've tried modifying the shell command as follows:
Shell "C:\PROGRA~1\MICROS~1\root\Office16\MSACCESS.EXE \\Vs300\rental_public\OFFICE~1\SHARED~1\SSDATA~1.MDB /X Upload_Manheim", vbMaximizedFocus
When I try to run my macro, I'm getting a file not found error message. I believe the 2nd half of the shell command is fine, so I believe it is the issue is in the 1st half of the shell command.
The database being opened is an Access 2000 database. I'm not sure what is wrong.

Instead of going thru the command line you could stay inside your Excel Macro and do the same without making reference to the location of the Access application. Instead you can create a new instance of MS Access from within vba, open the Access database the contains the macro, and then run the macro.
Something like:
Dim accApp As Access.Application
Dim db As Object
Set accApp = CreateObject("Access.Application")
accApp.OpenCurrentDatabase "Your database location\dbName", True
Set db = accApp.CurrentDb
With db
DoCmd.RunMacro "MacroNameHere"
End With
Set accApp = Nothing
Set db = Nothing
Good luck!

Related

Why isn't my script able to locate my excel file when given correct filepath?

I have a .vbs script that opens two excel files and copies the contents of a sheet from the first file into the second file. It's supposed to run daily via task scheduler.
The script ran normally until the excel files in question were recently modified and slightly renamed - I went through the script and edited the filenames accordingly after the changes were made, triple checking that the names and filepaths matched up.
Everything ran fine for a few weeks after the changes but now the script fails immediately after starting, giving me an error claiming that the file can't be located even though the file is located at the given path. The error code is 800A03EC.
This is the first chunk of code in the script, including line 7 which seems to be throwing the error:
Dim objApp ' as excel object
Dim x, y ' as workbook
Set objApp = CreateObject("Excel.Application")
objApp.DisplayAlerts = False
objApp.Visible = False
Set x = objApp.Workbooks.Open("S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\ORION_FPFOCUS.xlsm")
Set y = objApp.Workbooks.Open("S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\FPFocusPasteSpecialValues.xlsb")
Dim WSx, WSy ' as excel worksheet
Set WSx = x.Worksheets("FPSUP")
Set WSy = y.Worksheets("FPFOCUS-COPY")
WSy.Range("B1").value = FormatDateTime(Now)
objApp.Application.Run "ORION_FPFOCUS.xlsm!Auto_Open"
The excel files in question are both located in the same directory:
S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\ORION_FPFOCUS.xlsm
S:\Work (Public)\PORT MGMT & TRADING\PORT MGMT FORMS\FPFocusPasteSpecialValues.xlsb
And the script is located here:
C:\Users\bserv\Documents\CopyFPFocus.vbs
The S drive isn't a physical drive, it's a virtual drive hosted by a service called Workplace. I can navigate through it and open the excel files manually just fine.
I initially thought it was a user privilege issue with task scheduler, but I've selected the 'run with highest privileges' option and the script is still failing. I also went through the privacy/trust settings in Excel to make sure the script wasn't being denied access, but I don't see any settings that would disable the script from working, and I also know that all these settings haven't changed since the script was working, so I don't see how they could be potential causes.
When I try running the code manually via cscript in the command line, it returns this error:
C:\Users\bserv\Documents\CopyFPFocus.vbs(25, 4) (null): The remote procedure call failed.
This is line 25 of the script for reference:
objApp.Run "RefreshAllStaticData"
When I try again by running command prompt as an admin, I get the same error I got initially. Sorry, is it possible the file was moved renamed or deleted.
The part that really confuses me is that the script ran fine for some time after the changes - so I'm really unsure about what actually changed to cause this issue to randomly pop up.
One other thing I've noticed is that upon opening the excel files I get a popup saying they're in use and locked for editing by me. I can't remember if this popup was showing up before the issue started. The other users on the network have been accessing these files regularly long before the script started failing, so I don't see how that could be the issue. The error code/message also doesn't seem to correspond with this being the problem.
I'd appreciate any help or insight into this issue. Thank you!

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

Using functional application ID could not create object for WScript.CreateObject("Excel.Application")

Maestro runs with functional application ID and calls a Powershell script file
The PS script file calls a batch file - Run.bat
The batch file calls a Windows Script file (cscript.exe ...xxx.wsf)
The WSF runs a VBS program
It calls an Excel macro.
But the VBS program fails in the step where it tries to create Excel object and fails with the message "Could not create an object named excel.Application".
This script is working when user manually executes run.bat file.
Maestro also is working when functional application id credentials were used to login the server while maestro runs Run.batch file.
Please help why maestro could not create excel object in non-interactive mode i.e. user who runs the process is not actively logged in to the server.
Code in run.bat file:
cscript.exe ..\..\run.wsf
Code in run.wsf file:
<script language="vbscript" src="..\Run.vbs"></script>
Code in run.vbs file:
Dim xlApp, xlBook
Set xlApp = WScript.CreateObject("Excel.Application") -- Program fails here
Set xlBook = xlApp.Workbooks.Open(fnGetAbsolutePath(xlsFile))
I found the problem. Excel dcom-identity settings had been set as "interactive user" in that server which caused non-interactive excel requests run using interactive user's id. When I changed the setting below, it worked.
1: start->run and type 'DCOMCNFG'
2: Open 'DCOM Config' and locate 'Microsoft Excel Application'
3: Set its identity to 'The Launching User'.

VBscript Can't Find Excel File

I am attempting to use VBscript to open an excel file. However, when I run the script, it says the file cannot be located. I am pretty certain I have the file path correct. Is it possible that something else is causing my code to fail?
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook =
objExcel.Workbooks.Open("C:\Users\Guest\Documents\Projects\1A.xlsx")
Set objExcel = Nothing
Set objWorkbook = Nothing
As mentioned in the comments
In 9 out of 10 cases, this is permission related
The likeihood is (if you have already confirmed the file path is correct) that the VBScript does not have the permission required to access the file path, but due to the way elevation works along with UAC on most Windows Operating Systems means that VBScript doesn't know about the path, so it isn't reported as a access permission error.
As the path in question refers to a User Profile path the chances of it being permissions related increases.
To fix the problem the host process running the VBScript (wscript.exe or cscript.exe) needs to be run using elevated privileges. You can do this by opening an elevated command prompt (Run as Administrator context menu option) and specifying the host process followed by the script path.
Something like;
cscript.exe "yourscript.vbs"
From a windows command prompt type
c:\ dir C:\Users\Guest\Documents\Projects\1A.xlsx
The file could have been saved with a different file extension, or if explorer is hiding extensions and a user has provided the extension on save it might be called 1A.xlsx.xslx
Windows explorer might be hiding data. If you can see it in explorer, right click the file > properties > details.
The Name attribute should tell you exactly what the file is named on disk and the Folder path should give you the path.
You can combine the two to give the full path to the file on disk

VB Macros for Office 2016 for Mac require Permissions every time they try to access a file! Is there any way to get around this behavior?

Any VB Macro in Office 2016 shows a dialog box to the user asking for permission, every time the Macro tries to access a file! Is there a way to avoid it.
Unlike VB Macros in Office for Mac 2011, VB Macros in Office 2016 for Mac do not have access to external files by default. The Office 2016 for Mac apps are sandboxed and hence they lack the required permissions to access external files. Existing macro file commands are changed to prompt the user for file access if the app doesn’t already have access to it. This means that macros that access external files cannot run unattended; they will require user interaction to approve file access the first time each file is referenced.
Developers should use the GrantAccessToMultipleFiles command (see following section) to avoid this experience. This command lets your app get permission for all the files at one time, thereby avoiding a difficult user experience.
GrantAccessToMultipleFiles
This lets you input an array of file paths and prompt the user for permission to access them.
Boolean GrantAccessToMultipleFiles(fileArray)
Parameters
fileArray -- An array of POSIX file paths.
Return Values
True - The user grants permission to the files.
False - The user denies permission to the files.
Note: Once granted, the permissions are stored with the app and user need not grant permission to the file anymore.
Example: 
 
Sub requestFileAccess() 
 
'Declare Variables 
    Dim fileAccessGranted As Boolean 
    Dim filePermissionCandidates
 
 'Create an array with file paths for which permissions are needed 
    filePermissionCandidates = Array("/Users/<user>/Desktop/test1.txt", "/Users/<user>/Desktop/test2.txt")
 
'Request Access from User 
    fileAccessGranted = GrantAccessToMultipleFiles(filePermissionCandidates) 'returns true if access granted, false otherwise 
     
 
End Sub
I wanted to delete a file in Excel using VBA's Kill syntax and got the permission prompt when the VBA attempted to execute the command. My script is supposed to run once every 3 minutes day and night so responding to separate prompts wouldn't cut it.
To workaround the issue, I created a wrapper for VBA's Kill function called myKill. To implement it I:
Globally replaced all calls to Kill with myKill in my VBA code.
Added a new VBA subroutine called myKill (code below)
Created an AppleScript file to actually remove the file (code below)
Granted Excel Full Disk access in System Preferences/Security & Privacy/Privacy. Not sure this step was necessary but I mention it as it's my current configuration. It's worthless without the first three steps.
Here is the myKill subroutine:
Sub myKill(fname As String)
Dim s As String
If Left(Application.OperatingSystem, 3) = "Mac" Then
s = AppleScriptTask("Kill.applescript", "Kill", fname)
Else
Kill fname
End If
End Sub
Here is the Kill.applescript file contents:
on Kill(fileName)
# implementation of vba kill command on Mac. Mac sandboxes Microsoft's
# kill command
tell application "System Events" to delete alias fileName
end Kill
The Kill.applescript file must be stored in
/Users/your user name/Library/Application Scripts/com.microsoft.excel/Kill.applescript
The first time the Apple Script executes, Mac OS will ask for permission for Excel to manipulate files in the directory where the file to be deleted is located. Once given, future file deletes in the directory won't trigger the permission request. I tested that by exiting Excel, reentering and deleting another file.
RANT
How anyone thought making programmers jump through all these hoops or click "OK" each time a file had to be deleted was an acceptable implementation is beyond me. Because someone in Microsoft dropped the ball on abstracting simple file manipulations like Kill over 10,000 programmers have seen this web page trying to figure out what they have to do to delete a file in Microsoft Excel.
Yo Microsoft VBA Project Manager! I'm talking to you! Your job exists because Joel Spolsky convinced Bill Gates that a macro language for Excel was a good idea despite Gates' doubts. Your job is to ensure that Excel VBA abstracts os weirdness so programmers can get their job done and not have to hack in another language.

Resources