Google Chrome always says, “Google Chrome was not shut down properly” [duplicate] - google-chrome

This question already has answers here:
How to gently close Chrome using CMD or VBS?
(3 answers)
Closed 2 years ago.
I using in the VBS file script this code for closing Chrome browser automatically
Set objExec = browobj.Exec("tasklist /fi " & Chr(34) & "imagename eq chrome.exe" & Chr(34))
If Not InStr(1, objExec.StdOut.ReadAll(), "INFO: No tasks", vbTextCompare) Then
browobj.Run "taskkill /f /t /im chrome.exe", 0, True
End If
the problem is that when i reopen the browser always with
Set browobj = CreateObject("Wscript.Shell")
siteA = "http://XXXXXXX/"
browobj.Run "chrome -url " & siteA
I have error
Google Chrome was not shut down properly
What's wrong?
Why is this happening?

Refer to the answer of #tuxy42 : here
You can write to open chrome browser like this : Open_Chrome_Browser.vbs
Set ws = CreateObject("Wscript.Shell")
siteA = "https://stackoverflow.com/questions/62516355/google-chrome-always-says-google-chrome-was-not-shut-down-properly"
ws.Run "chrome -url " & siteA
And if you want to close it safely : safely_close_chrome_browser.vbs
Set ws = CreateObject("Wscript.Shell")
psCommand = "Cmd /C powershell -command ""Get-Process chrome | ForEach-Object { $_.CloseMainWindow() | Out-Null}"""
ws.run psCommand,0,True

Related

How to run .vbs through .bat file to convert .xls to .csv

I am completely new to scripting, so please forgive my ignorance.
(Running Windows 10)
I found a working solution to convert .xls files to .csv using the .vbs from this post:
Convert xls to csv.
The files I'm working with have multiple sheets, and the vbs works by dragging the file(s) onto the vbs file icon to execute. I don't understand how the vbs gets the input arguments. I copied this code posted by Chris Rudd
'Courtesy of Chris Rudd on stackoverflow.com
'Modified by Christian Lemer
'plang
'ScottF
' https://stackoverflow.com/questions/1858195/convert-xls-to-csv-on-command-line
'* Usage: Drop .xl* files on me to export each sheet as CSV
'* Global Settings and Variables
'Dim gSkip
Set args = Wscript.Arguments
For Each sFilename In args
iErr = ExportExcelFileToCSV(sFilename)
' 0 for normal success
' 404 for file not found
' 10 for file skipped (or user abort if script returns 10)
Next
WScript.Quit(0)
Function ExportExcelFileToCSV(sFilename)
'* Settings
Dim oExcel, oFSO, oExcelFile
Set oExcel = CreateObject("Excel.Application")
Set oFSO = CreateObject("Scripting.FileSystemObject")
iCSV_Format = 6
'* Set Up
sExtension = oFSO.GetExtensionName(sFilename)
if sExtension = "" then
ExportExcelFileToCSV = 404
Exit Function
end if
sTest = Mid(sExtension,1,2) '* first 2 letters of the extension, vb's missing a Like operator
if not (sTest = "xl") then
if (PromptForSkip(sFilename,oExcel)) then
ExportExcelFileToCSV = 10
Exit Function
end if
End If
sAbsoluteSource = oFSO.GetAbsolutePathName(sFilename)
sAbsoluteDestination = Replace(sAbsoluteSource,sExtension,"{sheet}.csv")
'* Do Work
Set oExcelFile = oExcel.Workbooks.Open(sAbsoluteSource)
For Each oSheet in oExcelFile.Sheets
sThisDestination = Replace(sAbsoluteDestination,"{sheet}",oSheet.Name)
oExcelFile.Sheets(oSheet.Name).Select
oExcelFile.SaveAs sThisDestination, iCSV_Format
Next
'* Take Down
oExcelFile.Close False
oExcel.Quit
ExportExcelFileToCSV = 0
Exit Function
End Function
Function PromptForSkip(sFilename,oExcel)
if not (VarType(gSkip) = vbEmpty) then
PromptForSkip = gSkip
Exit Function
end if
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
sPrompt = vbCRLF & _
"A filename was received that doesn't appear to be an Excel Document." & vbCRLF & _
"Do you want to skip this and all other unrecognized files? (Will only prompt this once)" & vbCRLF & _
"" & vbCRLF & _
"Yes - Will skip all further files that don't have a .xl* extension" & vbCRLF & _
"No - Will pass the file to excel regardless of extension" & vbCRLF & _
"Cancel - Abort any further conversions and exit this script" & vbCRLF & _
"" & vbCRLF & _
"The unrecognized file was:" & vbCRLF & _
sFilename & vbCRLF & _
"" & vbCRLF & _
"The path returned by the system was:" & vbCRLF & _
oFSO.GetAbsolutePathName(sFilename) & vbCRLF
sTitle = "Unrecognized File Type Encountered"
sResponse = MsgBox (sPrompt,vbYesNoCancel,sTitle)
Select Case sResponse
Case vbYes
gSkip = True
Case vbNo
gSkip = False
Case vbCancel
oExcel.Quit
WScript.Quit(10) '* 10 Is the error code I use to indicate there was a user abort (1 because wasn't successful, + 0 because the user chose to exit)
End Select
PromptForSkip = gSkip
Exit Function
End Function
This works well for my needs, but I want to run it hourly and save the .csv files to a new directory.
I tried to run the .vbs using the Task Scheduler, but it only opens the file in my text editor, it doesn't execute. My thought was to create a .batch file that runs the .vbs. I thought I could call the .vbs with PowerShell commands like this:
Start "XlsToCsv"
Start "XlsToCsv.vbs"
But both of those have the same effect of opening the .vbs in the text editor.
Perhaps a simpler question is, "How do I run a .vbs file from the PowerShell or the Command Prompt?"
Any help would be greatly appreciated.
This method works consistently in the batch environment, however cannot use doublequotes as would be advisable for filepaths with spaces.
Start filepath\name.vbs
no Doublequotes.
This method works Consistently in cmd.exe console, however fails in .bat programs:
WSscript.exe "filepath\name.vbs"
Wscript/Window Script host provides an environment to execute scripts in a variety of languages and Cscript starts a script in command line environment.
So, If you want to run your script in console use cscript.exe and wscript.exe if you don't want the console window. So, as T3RR0R mentioned you need to use WScript command to run it.
Sometimes, executing a VBscript in windows opens text editor rather than running it. This is due to changes in the default file associations. Some time antivirus will also do this in order to protect your system. In that case, you need to change the registry check this link https://superuser.com/questions/1108349/change-default-program-for-opening-vbs-files
Take look in this file.gif:
I'm understood that this only works if you're using the file vbs by Drag and Drop passing as arguments...
You can see instructions left by author about how to use in the vbs in 7rd line:
Drop .xl* files on me to export each sheet as CSV
Obs.: .xl* is equal to "any file with (.xl)"+any" == *.xlsx, *.xlsm...
Take look in this file.gif that you can see how to pass arguments in vbs, (is the same to cmd & bat) files by Drag and Drop:
This file.png show how to use arguments with the
The code you have tried are not using/passing any arguments (parameters), without pass any arguments, (one or more files) this will always fail!
If you need try using some like:
"XlsToCsv.vbs" "one_file_dot.extensio_equal_xlsx_.xlsx" "one_more_another_file_dot.extensio_equal_xlsx_too.xlsx"
rem :: observing if you are try in a different folder where the vbs + xlsx file are, try this:
"d:\folder\where\vbs\are\XlsToCsv.vbs" "d:\folder\where\xlsx\file1\are\1file_dot.extension_equal_xlsx_.xlsx" "d:\folder\where\xlsx\file1\are\one\more\are\too\one_more_another_file_dot.extensio_equal_xlsx_too.xlsx"
__
This is who I have using your vbs files in same folder where the files **.xlsx* are, so, no need passing the drive\folder path:
wscript 58924333.vbs "012019.xlsx" "022019.xlsx"
rem :: or ::
cscript 58924333.vbs "012019.xlsx" "022019.xlsx"
So sorry my limited English

vbs save and close all chrome and word documents

I am trying to create a vbscript that clears all my browser data in chrome, then closes all chrome windows.
I am having trouble closing word and outlook.
This it the code that works so far and clears chrome and closes the chrome browser:
Set WshShell = CreateObject("WScript.Shell")
set WshShell=WScript.CreateObject("WScript.Shell")
WshShell.run "chrome.exe"
Set WshShell = CreateObject("WScript.Shell")
set WshShell=WScript.CreateObject("WScript.Shell")
WshShell.run "chrome.exe"
WScript.Sleep (1000)
WScript.CreateObject("WScript.Shell").SendKeys("^h")
WScript.Sleep (2000)
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{ENTER}")
WScript.Sleep (2000)
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{TAB}")
WScript.CreateObject("WScript.Shell").SendKeys("{ENTER}")
WshShell.AppActivate("Google Chrome")
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8"
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2"
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1"
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16"
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32"
WshShell.run "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255"
Set objExec = Nothing : Set objShell = Nothing
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'Chrome.exe'")
Set oShell = CreateObject("WScript.Shell")
For Each objProcess in colProcessList
oShell.Run "taskkill /im chrome.exe", , True
Next
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("tasklist /fi " & Chr(34) & "imagename eq chrome.exe" & Chr(34))
If Not InStr(1, objExec.StdOut.ReadAll(), "INFO: No tasks", vbTextCompare) Then
objShell.Run "taskkill /f /t /im chrome.exe", 0, True
End If
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = 'notepad.exe'")
For Each objProcess in colProcessList
objProcess.Terminate()
Next
I am trying to close all of the word documents open and save them, basically (control s). I would like all of this to happen in one VBS file so that I can send this to my friends, and they can use it too easily.
I have researched online, but haven't found what I am looking for.
All the websites that I have looked at have either, only show how to close all documents without saving them or have not shown the process in VBS, instead using VBA or another scripting language.
I would appreciate if someone could help me write my script!
:)
Save and close all documents:
'get a handle to the already running Word instance
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
For closing all documents without saving change doc.Save to doc.Saved = True. That basically tells Word "this document was already saved, shut up".

Need vbscript to open URL links in webpages in Chrome browser not IE

At my place of work, we use IE11 and Chrome. We have a series of Flash files (created via Xelsius Crystal Dashboard) embedded in to HTM pages that access external XML data sources and we can only get them to work by using an HTA app which overcomes the adobe security restrictions in place.
Some of the other links we have on these web pages point to Google Drive Docs
and currently they ALWAYS open in IE when clicked. Trouble is, in my organisation, IE doesn't work well with Google Drive so we would like the links to open in Chrome - which does work with Google Docs
Asking people to change their default browser to Chrome doesn't work as the HTA app always opens in IE, so any subsequent links clicked also open in IE.
I've been told that it is possible to force a link to use Chrome using a vbscript using "Shell" command followed by the "path to Chrome" and the "URL to open".
That vbscript would be called with an onclick() event for any navigation button or link on our htm pages (e.g.
a onclick="openURLinChrome('link-to-open')"etc)
I have searched for days looking for a way to create this script to no avail, so I have joined here to seek help. There are a few threads here which I thought might help, but they didn't really apply to my problem.
Can anyone suggest a solution?
Many thanks
The key is to get the path to Chrome.Exe which can be in one of several locations on the drive. Fortunately, it is stored in the Registry; so one needs to read the registry from VB Script. Then it is just a matter of calling it with the URL. Since the path might have spaces in it, it needs to be enclosed in quotes.
Copy the following into notepad, save as OpenChrome.vbs and double-click it in Windows Explorer.
function readFromRegistry (strRegistryKey, strDefault)
Dim WSHShell, value
On Error Resume Next
Set WSHShell = CreateObject ("WScript.Shell")
value = WSHShell.RegRead (strRegistryKey)
if err.number <> 0 then
readFromRegistry= strDefault
else
readFromRegistry=value
end if
set WSHShell = nothing
end function
function OpenWithChrome(strURL)
Dim strChrome
Dim WShellChrome
strChrome = readFromRegistry ( "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe\Path", "")
if (strChrome = "") then
strChrome = "chrome.exe"
else
strChrome = strChrome & "\chrome.exe"
end if
Set WShellChrome = CreateObject("WScript.Shell")
strChrome = """" & strChrome & """" & " " & strURL
WShellChrome.Run strChrome, 1, false
end function
OpenWithChrome "http://www.microsoft.com"
siteA = "https://google.com"
siteB = "https://bing.com"
siteC = "https://yahoo.com"
Const OneSecond = 1000
Set browobj = CreateObject("Wscript.Shell")
browobj.Run "chrome -url "&siteA
WScript.Sleep OneSecond*20
browobj.Run "chrome -url "&siteB
WScript.Sleep OneSecond*6
browobj.Run "chrome -url "&siteC
WScript.Sleep OneSecond*6
Set browobj = Nothing
Something like this.
Sub openURLinChrome(strLink)
Set wshShell = CreateObject("WScript.Shell")
strChromePath = "C:\Program Files (x86)\Google\Chrome\Application\Chrome.exe"
wshShell.Run strChromePath & " -url " & strLink, 1, false
End Sub
set objAPP= createobject("shell.application")
objAPP.shellexecute"chrome.exe","www.google.com","","",1

HTML within VBScript as a popup

I've looked at Use HTML tags in VBScript and How can I call a vbscript function from html?, but I can't see what is wrong with my code. Can someone look it over and let me know why, when I click the OK button, the window doesn't close? I commented some lines out that I've tried and didn't work.
Dim objIE, objShell
Dim strDX
Set objIE = CreateObject("InternetExplorer.Application")
Set objShell = CreateObject("WScript.Shell")
strDX = "AT-0125B"
objIE.Navigate "about:blank"
objIE.Document.Title = "Covered Diagnosis"
objIE.ToolBar = False
objIE.Resizable = False
objIE.StatusBar = False
objIE.Width = 350
objIE.Height = 200
'objIE.Scrollbars="no"
' Center the Window on the screen
With objIE.Document.ParentWindow.Screen
objIE.Left = (.AvailWidth - objIE.Width ) \ 2
objIE.Top = (.Availheight - objIE.Height) \ 2
End With
objIE.document.body.innerHTML = "<b>" & strDX & " is a covered diagnosis code.</b><p> </p>" & _
"<center><input type='submit' value='OK' onclick='VBScript:ClickedOk()'></center>" & _
"<input type='hidden' id='OK' name='OK' value='0'>"
objIE.Visible = True
'objShell.AppActivate "Covered Diagnosis"
'MsgBox objIE.Document.All.OK.Value
Function ClickedOk
'If objIE.Document.All.OK.Value = 1 Then
'objIE.Document.All.OK.Value = 0
'objShell.AppActivate "Covered Diagnosis"
'objIE.Quit
Window.Close()
'End If
End Function
The ClickedOk() function is not part of the HTML source code of the new window. Your script starts a new Internet Explorer process, but HTML (or script) code in that process cannot use code from another process (in this case the script process):
yourscript.vbs --> ClickedOk()
| ^
| |
| X
v |
iexplore.exe --> <input onclick='VBScript:ClickedOk()'>
You'd need IPC methods for communicating with other processes, but browsers usually restrict this kind of access due to security considerations.
So, when you click 'OK', it looks for a ClickedOK function and cannot find it. Thus it will not work.
To make it work, try something like this:
objIE.document.body.innerHTML = "<b>" & strDX & " is a covered diagnosis code.</b><p> </p>" & _
"<center><input type='submit' value='OK' onclick='self.close();'></center>" & _
"<input type='hidden' id='OK' name='OK' value='0'>"

Can I share an MS-Access database application via Dropbox?

I have a small Access application that only 3 or 4 people will ever use, but I want them to be able to use it from different locations. Only one person will use it at a time. They are a non-profit with little to no funding. They don't have a server and are currently sharing an Excel spreadsheet back and forth between all of them. The easiest thing I could think of doing was to upload the .accdb file to a Dropbox account and have them access it from there. I know that you can publish it to SharePoint, but all they have are local copies of Office. Are there any issues with doing the Dropbox thing or are there any better alternatives any of you could suggest?
I agree that using a Dropbox folder as a shared location could possibly work provided that only one person had the database open at any one time. If more than one person opened the database at the same time then when Dropbox went to sync the file it could clobber somebody else's changes, or have sync conflicts, or perhaps just get horribly confused.
If I was to try using this approach I certainly would not rely on telling users to "always check if somebody else is using the database before opening it" or "always open the database in Exclusive mode". Instead, I would use a little launcher script like the following VBScript to manage access to the database. It uses a second file extension (.Available or .IN_USE) to indicate the status of the database file, makes a local (not synced) copy, opens that copy in Access, and then copies the updated file back to the Dropbox folder so it can be synced.
Option Explicit
Dim WshShell, fso, f, AccessPath, DropboxFolder, WorkingFolder, DatabaseName
Const TemporaryFolder = 2
DropboxFolder = "C:\Users\Gord\Dropbox\dbStorage\"
DatabaseName = "myDatabase.accdb"
Set fso = CreateObject("Scripting.FileSystemObject")
WorkingFolder = fso.GetSpecialFolder(TemporaryFolder) & "\"
If fso.FileExists(DropboxFolder & DatabaseName & ".Available") Then
Set f = fso.GetFile(DropboxFolder & DatabaseName & ".Available")
f.Name = DatabaseName & ".IN_USE"
WScript.Echo "Copying database file to working folder..."
f.Copy WorkingFolder & DatabaseName
Set f = Nothing
Set WshShell = CreateObject("WScript.Shell")
AccessPath = WshShell.RegRead("HKEY_CLASSES_ROOT\Access.MDBFile\shell\Open\command\")
AccessPath = Left(AccessPath, InStr(AccessPath, "MSACCESS.EXE") + 12)
WScript.Echo "Launching Access..."
WshShell.Run AccessPath & " """ & WorkingFolder & DatabaseName & """", 1, True
WScript.Echo "Copying database file back to Dropbox folder..."
fso.CopyFile WorkingFolder & DatabaseName, DropboxFolder & DatabaseName & ".IN_USE"
Set f = fso.GetFile(DropboxFolder & DatabaseName & ".IN_USE")
f.Name = DatabaseName & ".Available"
Set f = Nothing
Else
If fso.FileExists(DropboxFolder & DatabaseName & ".IN_USE") Then
MsgBox "The database is currently in use. Try again later."
Else
MsgBox "The database could not be found."
End If
End If
Set fso = Nothing
The launcher could be invoked by a shortcut whose target is
CSCRIPT.EXE C:\wherever\launchMyDatabase.vbs
This is an enhanced version of Gord Thompsons script which tries to inform the user to help them do the "right thing".
It also deals with exceptional behaviour such as bad internet access (it encourages the user NOT to use it!) and it also deals with the script being terminated by the user once access has been opened)
' This uses a second file extension (.Available or .InUse) to indicate the status of the database file,
' makes a local (not synced) copy inthe temp folder and opens that copy in Access.
' The updated file is copied back to the Dropbox folder so it can be synced.
' A backup fodler and file can be created with a date in the filename if the suer chooses to.
'
' The launcher could be invoked by a shortcut whose target is
'
' CSCRIPT.EXE C:\!AA\OpenFMFtoolDatabase.vbs
' Or to debug (it can open in VS if VS has been setup right with an external tool)
' CSCRIPT.EXE /X C:\!AA\OpenFMFtoolDatabase.vbs
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' This file is used to open and backup the FMFtool university and Subject database
'
' It can be invoked by a shortcut whose target is CSCRIPT.EXE C:\!AA\OpenFMFtoolDatabase.vbs
'
' See the tag #DOTHESE below for constants that need to be changed for each specific user
'Option Explicit
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' Supporting functions
'
Function LPad(MyString, MakeStringThisLong, PadWithThisChar)
Dim n: n = 0
If MakeStringThisLong > Len(MyString) Then n = MakeStringThisLong - Len(MyString)
LPad = String(n, PadWithThisChar) & MyString
End Function
Function BuildDateForFile()
Dim TheMonth, TheDay
TheMonth = LPad(Month(Date), 2, "0")
TheDay = LPad(Day(Date), 2, "0")
BuildDateForFile = DatePart("yyyy", Now) & TheMonth & TheDay & "_"
End Function
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' ----------------------------------------------------------------------------------------
' Main Procedure
'
Sub OpenDatabase()
' -----------------------------------------------------------------
' -----------------------------------------------------------------
' USER / MACHINE SPECIFIC #DOTHESE
Const SupportEmail = "mr#harveyfrench.co.uk"
' This script may prompt the user to contact support using this email address.
Const DropboxFolder = "C:\!AA\DropBox\"
' A typical value is "C:\Users\Gord\Dropbox\dbStorage\" Note that it must END WITH a backslash
' It is set to the name of the LOCAL folder (ie a folder on the PC running this script) which is synced with dropbox
' (or any internet based file sharing system like Dropbox, Onedrive, GDrive, etc)
Const DatabaseCalled = "University and Subject Database"
' The name of the database file without the file extension (ie no .accdb)
Const DatabaseExtension = ".accdb"
' The file extension (eg .accdb)
' -----------------------------------------------------------------
' -----------------------------------------------------------------
' General constants
Const TemporaryFolder = 2
Const TAGForINUSE = ".InUse"
Const TAGForAVAILABLE = ".Available"
Const TAGForOldLocalFile = ".OldFile"
Dim WshShell, f, AccessPath, WorkingFolder, DatabaseName
Dim FileNameWhenInUse, FileNameWhenAvailable
Dim DropBoxInUse, DropBoxAvailable
Dim DropboxBackupFolder, DropboxBackupFileName, DropboxDONOTBackupFileName
Dim LocalFile, OldLocalFile
Dim blnOpenLocalFile
' -----------------------------------------------------------------
' Use these lines when delivering the code
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
' -----------------------------------------------------------------
' Use may use these lines when writing the code
'Dim fso As Scripting.FileSystemObject
'Set fso = New Scripting.FileSystemObject
' -----------------------------------------------------------------
' About files and folders
DatabaseName = DatabaseCalled & DatabaseExtension
FileNameWhenInUse = DatabaseName & TAGForINUSE
FileNameWhenAvailable = DatabaseName & TAGForAVAILABLE
DropBoxInUse = DropboxFolder & FileNameWhenInUse
DropBoxAvailable = DropboxFolder & FileNameWhenAvailable
DropboxBackupFolder = DropboxFolder & "Backups"
WorkingFolder = fso.GetSpecialFolder(TemporaryFolder) & "\"
' eg often: C:\Users\Harvey\AppData\Local\Temp\
LocalFile = WorkingFolder & DatabaseName
OldLocalFile = LocalFile & TAGForOldLocalFile
blnOpenLocalFile = False
' -----------------------------------------------------------------
' WARN User
'
If vbNo = MsgBox("This will open " & DatabaseName & vbCrLf & _
vbCrLf & _
"DO YOU HAVE ACCESS TO THE WEB?" & vbCrLf & _
vbCrLf & _
"Do not click YES unless you are sure you do as the web is needed to prevent other people from opening the above file while you have it open. " & vbCrLf & _
vbCrLf & _
"NOTE 1: It is OK to loose web access once the file is opened - but others will not be able to use it again until you have web access (and have closed the file)." & vbCrLf & _
vbCrLf & _
"NOTE 2: If you click YES and you do not have web accesss, either you or someone else WILL LOOSE ALL changes made to the file!)", vbYesNo) Then
Exit Sub
End If
' ---------------------------------------------------------------------------------
' ---------------------------------------------------------------------------------
'
' Main processing -
' The file is only opened if it is available (ie not in use by another person).
' It can also be opened if it is determined that the file was not copied back to the dropbox folder
' but was "accidentally" left in the temp folder
' When it is opened the file is renamed on dropbox to indicate it is unavailable
'
If fso.FileExists(DropBoxAvailable) Then
Set f = fso.GetFile(DropBoxAvailable)
' This renames the file on dropbox to be "InUse"
f.Name = FileNameWhenInUse
'
' Allow dropbox to upload the file ASAP (if possible, force dropbox to sync here )
'
WScript.Echo "Copying database file to temp folder..."
f.Copy LocalFile
Set f = Nothing
blnOpenLocalFile = True
Else
If fso.FileExists(DropBoxInUse) Then
If fso.FileExists(LocalFile) Then
MsgBox "The database was found locally and will be opened " & vbCrLf & _
vbCrLf & _
"(it had already been previoulsy opened by you, but not written back to the dropbox folder (perhaps a process crashed)."
blnOpenLocalFile = True
Else
MsgBox "The database is currently in use by someone else. Try again later."
blnOpenLocalFile = False
End If
Else
MsgBox "The database could not be found on dropbox " & vbCrLf & _
vbCrLf & _
"(Both " & TAGForINUSE & " and " & TAGForAVAILABLE & " versions are missing from dropbox!)."
If fso.FileExists(LocalFile) Then
MsgBox "A Copy of the file exists locally on your computer. " & vbCrLf & _
vbCrLf & _
"(The file will be opened and written back to dropbox as usual BUT - " & vbCrLf & _
"please email " & SupportEmail & " as this situation should not be arising!)."
blnOpenLocalFile = True
Else
If fso.FileExists(OldLocalFile) Then
MsgBox "A backup copy of the local file exists (know as the OldLocalFile)" & vbCrLf & _
vbCrLf & "Email support on " & SupportEmail & vbCrLf & _
"to find out what to do (as this is a really wierd situation)."
Else
MsgBox "A backup copy of the local file DOES NOT EXIST " & vbCrLf & _
vbCrLf & "Email support on " & SupportEmail & vbCrLf & _
"..but being honest you may be in a really bad pickle, but if you've been taking backups you'll be fine!"
End If
blnOpenLocalFile = False
End If
End If
End If
If blnOpenLocalFile Then
' ---------------------------------------------------------------------------------
' Take a daily backup
'
If Not fso.FolderExists(DropboxBackupFolder) Then
WScript.Echo "Creating backup folder."
fso.CreateFolder DropboxBackupFolder
End If
DropboxBackupFileName = DropboxBackupFolder & "\" & BuildDateForFile() & DatabaseName
DropboxDONOTBackupFileName = DropboxBackupFileName & ".NoBackup"
DropboxBackupFileName = DropboxBackupFileName & ".Backup"
If Not (fso.FileExists(DropboxBackupFileName)) And Not (fso.FileExists(DropboxDONOTBackupFileName)) Then
If vbYes = MsgBox("Do you want to take a daily backup? " & vbCrLf & _
vbCrLf & "(click YES if a lot of work has been done since the last backup was taken. " & vbCrLf & _
" If in doubt click YES)", vbYesNo) Then
WScript.Echo "Creating daily backup file."
fso.CopyFile LocalFile, DropboxBackupFileName
Else
' Create an empty text file to flag no backup is wanted that day
WScript.Echo "No daily backup file will be created."
fso.CreateTextFile (DropboxDONOTBackupFileName)
End If
End If
' ---------------------------------------------------------------------------------
' Open the file
'
Set WshShell = CreateObject("WScript.Shell")
AccessPath = WshShell.RegRead("HKEY_CLASSES_ROOT\Access.MDBFile\shell\Open\command\")
AccessPath = Left(AccessPath, InStr(AccessPath, "MSACCESS.EXE") + 12)
WScript.Echo "Launching Access and Opening temp database file: " & vbCrLf & LocalFile
WshShell.Run AccessPath & " """ & LocalFile & """", 1, True
WScript.Echo "Copying temp database file back to Dropbox folder..."
fso.CopyFile LocalFile, DropBoxInUse
Set f = fso.GetFile(DropBoxInUse)
f.Name = FileNameWhenAvailable
Set f = Nothing
' Make another copy of the file that was copied to the dropbox folder, then delete the original file
' (This might help stop a bad catastrophe!)
WScript.Echo "In Temp Folder: Copying temp database file to be .oldfile"
fso.CopyFile LocalFile, OldLocalFile
WScript.Echo "In Temp Folder: Deleting temp database file "
fso.DeleteFile LocalFile
End If
Set fso = Nothing
End Sub
' Do the work!
OpenDatabase
I know this is an old question, I do not think it is possible to do this safely. The issue is that LDB files, which are the files that manages the share of connections to the database can lose track of open state. This occurs when external files are joined to the primary database via JOIN/IN type constructs. When this occurs the Jet/ADO engine still has locks on files even if the application exits, as the file specified in the IN clauses is opened but not closed when the query completes. Then DropBox creates conflicted copies of files and data is lost.