Open External Password Protected Database with Automation in Access Runtime Version - vba

I want to open an external password protected database in separate window. I have tried follwoing code (shared by Isladogs from MendipDataSystems on some forum):
Public Function RunExternalDatabase() As Boolean
Dim app As Access.Application, strPath As String
'Start a new MSAccess application
Set app = New Access.Application
'Open the remote database and run a macro, then close the remote database
With app
'Syntax: .OpenCurrentDatabase(filepath, Exclusive, strPassword) - the last 2 items are optional
strPath = "C:\Programs\MendipDataSystems\JATFA\JATFA.accdb" 'replace with your file path
.OpenCurrentDatabase strPath, True, "password"
' .DoCmd.RunMacro "mcrRefreshPersTable" 'run your macro
.CloseCurrentDatabase 'closes external database as that is current
End With
'Quit the spawned app
app.Quit acQuitSaveNone
Set app = Nothing
'Quit the current app - optional
Application.Quit acQuitSaveNone
End Function
Above code works fine in full Access but gives error for those users who are using Access runtime version. The line of code that gives error is Set App = New Access.Application.
How can I fix it OR is there any alternative method to get the purpose done?
Purpose is to open the password encrypted database in separate window in Access runtime version without entering the password manually.
Best Regards

Related

How to close an Access database and open a newdatabase on the same instance, same user, with VBA?

There are three separate shared Access databases (tampa1, tampa2, tampa3), multiple users access them. Each user needs to be able to switch databases (using a dropdown list/combo) at any given time, when the user does so. Goal: the program should be able to open the new database in the same instance and close the exiting database (in either order) if it was opened by the same user. I don't want the database to close another instance of any of the three databases opened by different user.
I was able to create the first part of the code, opening the database (although I am not sure if it has been opened in same or different instance). I created a code to close the exiting db (Applicaton.quit), however when I run the code, both databases are closed.
Public Sub Opendb21()
Static acc As Access.Application
Dim db As DAO.Database
Dim strDbName As String
Set acc = New Access.Application
strDbName = "C:\Users\YOURNAME\Documents\Opening multiple db Test\tampa2.accdb"
Set db = acc.DBEngine.OpenDatabase(strDbName, False, False)
acc.OpenCurrentDatabase strDbName
acc.Visible = True
'db.Close
'Set dbRemote = acc.CurrentDb
Set db = Nothing
'Closing the current db tampa1
Forms!Form1.cmd_CloseAccess_Click
End Sub
'Second sub
'Closing cmd -macro converted to VBA code
'This is on Form1, tampa1 database
Public Sub cmd_CloseAccess_Click()
DoCmd.Quit acQuitSaveAll
End Sub
I am expecting the program to close the current db (tampa1); open the second db (tampa2), but the program closes both instead. I need a way to make sure the code doesn't close an instance currently open by different user.
thank you for your hints! I found the solution to the issue by reading another Stack overflow posting, here is the link to that posting:
Access: Shell cmd Open MDB
I was missing the command "Application.UserControl=True" , which makes the application persistent and visible. I created a form which has a combo box that lists the databases I want to switch to. The variable ("OpenWhat")captures the name of the specific database and passes the parameter to a Module Sub, where it then completes the string by adding the rest of the information. After the new database is open, the Form in the first database closes the calling database.
Here is my particular piece of code:
Private Sub cbb_open_otherdb_AfterUpdate()
Dim OpenWhat As String
OpenWhat = Forms!Form1.cbb_open_otherdb.Value
Call Opendb(OpenWhat)
Forms!Form1.cmd_CloseAccess_Click
End Sub
Public Sub cmd_CloseAccess_Click()
On Error GoTo cmd_CloseAccess_Click_Err
DoCmd.Quit acQuitSaveAll
cmd_CloseAccess_Click_Exit:
Exit Sub
cmd_CloseAccess_Click_Err:
MsgBox Error$
Resume cmd_CloseAccess_Click_Exit
End Sub
Option Compare Database
Option Explicit
Public Sub Opendb(ByVal OpenWhat)
Dim objApp As Access.Application
Set objApp = New Access.Application
objApp.UserControl = True
objApp.OpenCurrentDatabase "C:\Users\YOURNAME\Documents\Opening multiple db Test\" + OpenWhat & ".accdb"
MsgBox ("Opening ") & OpenWhat
Debug.Print OpenWhat
Set objApp = Nothing
End Sub
I copied similar code to the other two databases to create a navigation ring.
Thank you for your help!

Writing to Command Line Not Working

An application I need to use (USB capture utility) has a .cmd version that I can call from my Visual Basic code. I am able to launch the application and put it in "command line mode" like this:
Public Class MyClass
Dim StreamWriteUtility As System.IO.StreamWriter
Dim StreamReadUtility As System.IO.StringReader
Dim ProcessInfo As ProcessStartInfo
Dim Process As Process
Public Sub StartUSBCapture(ByVal DataStorageLocation As String)
Dim ProcessInfo As ProcessStartInfo
Dim Process As New Process
ProcessInfo = New ProcessStartInfo("C:\FW_Qualification_Suite\data-center-windows\data-center\bin\datacenter.cmd", "-c ")
ProcessInfo.CreateNoWindow = True
ProcessInfo.UseShellExecute = False 'Must be changed if redirect set to True
ProcessInfo.RedirectStandardInput = True
Process = Process.Start(ProcessInfo)
SWUtility = Process.StandardInput
While True
SWUtility.WriteLine("run") 'Looping for test to ensure this isn't a timing issue
End While
End Sub
End Class
This launches the application and opens a separate command line window that should accept further commands (i.e., capture, run, stop, etc). However, I am having trouble getting those subsequent commands to show up in the command line window. I've tried redirecting the standard input of the process, but still nothing shows up in the console window.
Can anyone tell how I'm supposed to actually get these commands from my Visual Basic program into this application?

system.diagnostics.process will not open Excel file without Excel open first

I have a VB.Net application in which I have a general method to open documents that exist on the local drive using system.diagnostics.process.
Public Shared Function OpenFileWithProcess(ByVal lsFileNameWithPath As String, Optional ByVal lPrintOption As PrintOutputOption = PrintOutputOption.Preview)
Try
Select Case lPrintOption
Case PrintOutputOption.Preview
Dim P As System.Diagnostics.Process
P = Process.Start(lsFileNameWithPath)
If Not P Is Nothing Then
Dim handle As IntPtr = P.Handle
SetForegroundWindow(handle)
End If
Case PrintOutputOption.Print
Dim Proc As New Process
Proc.StartInfo.FileName = lsFileNameWithPath
Proc.StartInfo.UseShellExecute = True
Proc.StartInfo.Verb = "Print"
Proc.Start()
End Select
Catch ex As Exception
If oSQL.Key_Developer Then
Stop
End If
Throw ex
End Try
End Function
On some computers that have Windows8 and OFfice2010, this method will not open an Excel file without Excel being open first. Instead it will error with "Run-Time Error 2147467259 (80004005). An error occurred in sending the command to the application".
If Excel is open prior to the method call, then the file opens just fine.
Some additional environment info:
- VB.NET application compiled to .Net Framework 4
- Application is deployed on Windows 7, 8 and 8.1
I could trap for the error and try to start the process again using the Excel session that hangs open after the error but I'm wondering if someone can tell me or help me figure out what is going on here.
Thank you for your time.

VBA: Get Excel FileDialogOpen to point to "My Computer" by default

I'm trying to get excels save and open dialog boxes to open to "my computer" by default so the user can select a drive from there.
I have got the dialog boxes to open to any path on any drive or my documents etc but can't seem to find a way for it to open to my computer.
This is the code i'm using at the moment and it works fine for a known path:
MsgBox objFolders("desktop")
ChDrive objFolders("desktop")
ChDir objFolders("desktop")
strFileName = appRemoteApp.Workbooks("Export Template.xlsm").Application.GetSaveAsFilename(objFolders("desktop") & "\Replica Export " & UserName & " " & Format(Date, "yymmdd") & ".xlsm", FileFilter:="Excel Macro Enabled Workbook (*.xlsm), *.xlsm,")
Also, I have found this from this site.
If you paste ::{20D04FE0-3AEA-1069-A2D8-08002B30309D} into windows explorers address bar it takes you to my computer but if I use this in my VBA code
ChDir "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
it says it cant find the directory or something. So not sure if there is a work around for this or something.
This did not work either:
ChDir "C:\WINDOWS\explorer.exe /root,,::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
The reason i'm wanting to have the dialog boxs open to computer is that we will be hosting the excel doc on a windows server with access though RemoteApp and remote desktop. The users will not have access (rights) to the servers drives and folders etc, they will only have access to their own drives on their local machines which will be mapped and are visible under the servers "My Computer" folder for lack of a better word. The master document on the server generates a replica using VBA code and is then saved to the users local hard drive.
AFAIK there is no pure VBA solution to override the original behaviour. You can use an alternative from Robert Mearns answer but it doesn't show the windows form so it's less customizable.
Follow this answer if you want to achieve the exact effect - FileOpenDialog.
You can print all the environmental variables using the Environ$() function. This will not show any variable directly pointing to MyComputer therefore you can't pass it to the .InitialFileName property.
MyComputer is not a physical location that you can access through cmd. I think of it as an abstract Interface and it's quite difficult to explain how VBA and .InitialFileName uses a string to access a location.
Well, the only workaround the problem I can think of it's to use an external library written in for example C# that can access the MyComputer.
It's easier than it sounds!
Follow the below steps to create your Custom OpenFileDialog.
You need a Visual Studio Express For Desktop - it's free to download and use.
After installation - run as Administrator! (it's necessary for the libraries to get registered)
Select File and New Project. Rename it to CustomOFD and and hit the OK.
Right-click the CustomOFD Project in the Solution Explorer and Select Add References
Add references to the System.Windows.Forms as shown in the below img
Right-click Class1.cs in the Solution Explorer and rename it to CustomOFD.cs.
Double click your CustomOFD and replace the code with the one from below
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CustomOpenFileDialog
{
[InterfaceType(ComInterfaceType.InterfaceIsDual),
Guid("541EDD34-4CDC-4991-82E9-6FC23F904B5B")]
public interface ICustomOFD
{
DialogResult ShowDialog();
string FileName();
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("E33102F0-B3C0-441C-8E7A-B9D4155A0D91")]
public class CustomOFD : ICustomOFD
{
private OpenFileDialog box = new OpenFileDialog();
public CustomOFD()
{
box.Multiselect = false;
box.Title = "Select file";
box.InitialDirectory = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}";
}
public DialogResult ShowDialog()
{
return box.ShowDialog();
}
public string FileName()
{
return box.FileName;
}
}
}
Note: you can generate a new GUID for your own class using the Tools => Create GUID and replace it with your own, if you wanted to...
Right-click the CustomFileOpenDialog in the Solution Explorer and select Properties
In the Properties window go to Application tab and click Assembly Info and tick the Make COM-Visible box
Then go to the Build tab and tick Register for COM interop
Right-click the project and select Build from the menu
Now look in the Output tab as it shows you where the library was compiled to
usually its
c:\users\administrator\documents\visual studio 2012\Projects\CustomOpenFileDialog\CustomOpenFileDialog\bin\Debug\CustomOpenFileDialog.dll
Ok. Now save and close VS.
Open Excel and go into VBE ALT+F11 and insert a standard module
Click Tools on the menu bar and select References
Click the Browse button and navigate to the CustomOpenFileDialog.tlb file and click OK add to the list of references
Copy paste the code for module
Option Explicit
Sub Main()
Dim ofd As New CustomOFD
Set ofd = New CustomOFD
ofd.ShowDialog
Debug.Print ofd.Filename
End Sub
finally, run the sub and enjoy the computer as the default location for the customized OpenFileDialog box!
I cannot see a way to use the GetSaveAsFilename or similar dialogs to open on Computer or My Computer.
It is possible to prompt the user to select a folder using VB Script.
The root displayed is Computer and the user can select a folder.
The file can then be saved to the selected folder programatically.
Sub Test()
MsgBox BrowseForFolder(MyComputer)
End Sub
http://technet.microsoft.com/library/ee176604.aspx
Function MyComputer() As Variant
Dim objShell As Object, objFolder As Object
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(&H11&)
MyComputer = objFolder.self.Path
Set objShell = Nothing
Set objFolder = Nothing
End Function
http://www.vbaexpress.com/kb/getarticle.php?kb_id=405
Function BrowseForFolder(Optional OpenAt As Variant) As Variant
Dim ShellApp As Object
Set ShellApp = CreateObject("Shell.Application"). _
BrowseForFolder(0, "Please choose a folder", 0, OpenAt)
On Error Resume Next
BrowseForFolder = ShellApp.self.Path
On Error GoTo 0
Set ShellApp = Nothing
End Function
.InitialFileName = "Computer"
Works for me with FileDialog(msoFileDialogFolderPicker)
Tested on Windows Vista - Excel 2007

Have Windows Authentication use default login page instead of popup dialog in Sharepoint 2010

Is there a way to have simple windows authentication for a public facing site (anonymous viewing is enabled so as to view the login page) but insatead of it popping up the windows auth dialog, to use a login page (aspx). I saw something similar when i switched to mixed mode authentication. SharePoint has a dropdown with "windows authentication" or "forms authentication". What i need is something similar, but just the "windows authentication" option.
I've seen similar questions on SO, but they all involve creating a custom login page. The ideal solution would involve no new pages and no coding.
Is this possible?
This could be done by launching the sharepoint page's address in internet explorer, and using some pinvoke api to send keys or settext to the login box.
I fanagled this setup for a vb.net forms application. It works on my XP. I haven't tried it in Windows 7 yet, but I'm sure it needs some adjustment for it to work there.
This uses a library called WindowScraper, from here: http://www.programmersheaven.com/download/56171/download.aspx
This library has a bunch of winapi and pinvoke built in. If your assembly won't allow it (because you are using VS 2010, perhaps), saying it doesn't have a strong name, then use SharpDevelop and rebuild the solution after adding your own certificate.
Then put the dll in your application directory and add a reference.
Then add the imports:
Imports WindowScrape
Imports WindowScrape.Constants
Imports WindowScrape.Types
Finally, the code (put all this in a module or class):
Private Property PortalAddress As String = "http://myportal#somewhere.com"
Private Property logintitle As String = "Connect to myportal#somewhere.com"
Public Sub openPortal()
If My.Computer.Info.OSFullName = "Microsoft Windows XP Professional" then
LoginToPortalXP()
Else
msgbox("Someday, we will be able to log you in automatically" & vbCr & "But it isn't ready yet.")
End If
End Sub
Private Function IsWindowReady(Optional ByVal timeout As integer = 10000)
Dim isready As Boolean = false
Dim timer As Integer = 1000
Do Until Not loginBox is nothing or timer = timeout
Thread.Sleep(1000)
loginbox = HwndObject.GetWindowByTitle(logintitle)
timer = timer + 1000
loop
If Not loginbox is nothing then isready = true
Return isready
End Function
Sub LoginToPortalXP()
Try
Dim TheBrowser As Object = CreateObject("InternetExplorer.Application")
TheBrowser.Visible = True
TheBrowser.Navigate(PortalAddress)
If Not IsWindowReady then debug.print("failed") : Exit sub
Dim sys As HwndObject = loginbox.GetChildren(1) 'SysCredential
sys.GetChildren(1).Text = "myUserName" 'username box
Thread.Sleep(500)
sys.GetChildren(4).Text = "myPassword" 'password box
Thread.Sleep(500)
loginbox.GetChildren(2).Click() 'push the okay button
Catch ex As Exception
msgbox("ERROR AutoLogging into Portal: " & vbcr & & ex.Message)
Finally
End Try
End Sub
I added the timer just in case it takes longer. You can change the timeout, of course.