How to get workbook name of running excel instance using vbscript..? - excel

Dim objXL, strMessage
On Error Resume Next
Set objXl = GetObject(, "Excel.Application")
If Not TypeName(objXL) = "Empty" then
strMessage = "Excel Running"
Else
strMessage = "Excel NOT Running"
End If
MsgBox strMessage, vbInformation, "Excel Status"
Hey thanks alot buddy. This really brings me close to what am looking for, moving much closer to the solution.
Let me tell you my exact requirement/issue:
Actually my issue is that, from Java I am trying to find Excel instance with a particular workbook name but am not returned an Excel instance even though it appears. In my case I have an Excel opened with 2 workbooks "Book1" and "Book2" in it.
When am trying to find Excel with any of these workbook name, am given no result. To narrow down, this issue is observed only on one of my client machines. On rest machines this same java code working fine.
This started happening after uninstalling Excel2010 and installing Excel2007.
So what I am trying to do is that, want to create one vbscript where I can give the workbookname as an input and it will return me whether there is such Excel instance running with given workbook name.
Hey please guide me further towards creating such script where I will give the workbook name and script will find whether such Excel instance is running or not. Not an issue even if workbook name is passed as an hardcoded input in script. I will alter as per my workbook name.
Thanks for your previous reply and awaiting for this one too.. :))

If you potentially have more than one excel instance open than to detect if a specific workbook is open you could use:
This code to examine all open workbooks in all instances Can VBA Reach Across Instances of Excel?
Detect if the file is already in use. See Sid's suggestion from Detect whether Excel workbook is already open
Doug's suggestion to use GetObject to attach to a host instance where you know the workbook name. As per the Microsoft Support article you can use Set xlApp = GetObject("YourExcelName").Application to detect if "YourExcelName" is open in any instance
In the question that you initially asked, the code below uses GetObject to detect whether any instance is open, and if there is an ActiveWorkbook and what that name ie. From your edited question my three links above are more relevant than this code.
Dim objXL, WB, strMessage
On Error Resume Next
Set objXL = GetObject(, "Excel.Application")
Set WB = objXL.ActiveWorkbook
On Error GoTo 0
If Not TypeName(objXL) = "Empty" Then
If Not TypeName(WB) = "Nothing" Then
strMessage = "Excel Running - " & objXL.ActiveWorkbook.Name & " is active"
Else
strMessage = "Excel Running - no workbooks open"
End If
Else
strMessage = "Excel NOT Running"
End If
MsgBox strMessage, vbInformation, "Excel Status"""

I not use Excel, and I hope that the next code may give you a starting point.
But if you have many Excel instances running then should investigate future more yourself.
Dim objXL, strName, bFound, strMsg
On Error Resume Next
Set objXl = GetObject(, "Excel.Application")
On Error GoTo 0
If Err Then
MsgBox "Excel NOT Running", vbInformation, "Excel Status"
WScript.Quit(-1)
End If
strName = InputBox("Enter Workbook Name:", "Required")
If Len(strWBName) = 0 Then WScript.Quit(-2)
bFound = False
If objXL.Workbooks.Count > 0 Then
For Each wb In objXL.Workbooks
If wb.Name = strName Then
bFound = True
Exit For
End If
Next
End If
strMsg = "Workbook " & UCase(strName) & " is "
If bFound Then
MsgBox strMsg & "open", vbInformation, "Result"
Else
MsgBox strMsg & "not open", vbInformation, "Result"
End If
P.S. After reading Brettdj updated answer looks like GetObject can help for multiple Excel instances, so if that works you can capsule your test in a function.
Function IsWBookOpen(strWBook)
On Error Resume Next
Dim wb: Set wb = GetObject(strWBook)
IsWBookOpen = Not Err
End Function

You can capture the active workbook name with the following command. objXL.ActiveWorkbook.Name
Dim objXL, strMessage
On Error Resume Next
Set objXL = GetObject(,"Excel.Application")
If Not TypeName(objXL) = "Empty" then
strMessage = "Excel Running"
WScript.Echo "The active workbook name is " & objXL.ActiveWorkbook.Name
Else
strMessage = "Excel NOT Running"
End If
MsgBox strMessage, vbInformation, "Excel Status"

Related

From MS Access VBA close encrypted excel after failed password

I'm keeping an ID for API in an encrypted excel file (open to alternative suggestions) and using Microsoft access VBA to open the encrypted excel and extract the ID.
The issue is that it will not close excel if the password is incorrect. This code works fine if you enter the password correctly
Public Function getDeploymentID() As String
Dim fileLocation As String
fileLocation = "___DeploymentID.xlsx"
Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
Dim wb As Excel.Workbook
On Error GoTo getDeploymentID_ERROR
MsgBox "The development password is in a password protected excel. It will prompt you for the password next"
Set wb = Workbooks.Open(fileLocation, True)
'User must enter password to continue. If they don't it'll error out on above line
DoEvents
'Get deploymentID
getDeploymentID = wb.Worksheets("Sheet1").Cells(1, 1)
'Close it
'wb.Close 'will close workbook, won't close excel
wb.Application.Quit 'will close workbook and excel
DoEvents
GoTo getDeploymentID_Cleanup
getDeploymentID_ERROR:
Debug.Print "Failed to open DeploymentID excel file. Error " & err.Number & ":" & err.description
objExcel.Quit 'THIS IS NOT WORKING
DoEvents
getDeploymentID_Cleanup:
Set wb = Nothing
Set objExcel = Nothing
End Function
I believe you need to access the Workbooks collection through the objExcel.
Set wb = objExcel.Workbooks.Open(fileLocation, True)
Then,
wb.Close 'close workbook
objExcel.Quit 'quit excel app
References:
Workbook.Close
Application.Quit
Regarding the structure of the function, I would add the error handling at the bottom and call Resume to avoid the 2nd GoTo statement.
'...
On Error GoTo getDeploymentID_ERROR
'...
'Get deploymentID
getDeploymentID = wb.Worksheets("Sheet1").Cells(1, 1)
getDeploymentID_Cleanup:
wb.Close
objExcel.Quit
Exit Function
getDeploymentID_ERROR:
Debug.Print "Failed to open DeploymentID excel file. Error " & err.Number & ":" & err.description
Resume getDeploymentID_Cleanup
End Function

Save new file with filename cell value

I am working on making a universal production time sheet(wbTime) for each dept that will work across all shifts and lines. I have where all the necessary information is required to be entered, all the data getting copied into a table in another workbook(wbLog) and saved to be able to do analysis on the production data.
However, when it gets to trying to save the actual time sheet in the proper folder according to shift and machine line I start running into problems. I have it pulling part of the path from certain cells and the filename form the date the enter. It is getting to the last line and throwing a run-time error 1004 "Method 'SaveAs' of object_Worbook'failed".
I have only been playing with vba for 2 months so it is probably something small that I just do not see...
Sub TransferData()
If ActiveSheet.Range("E2").Value = "" Then
MsgBox "Operator Name Required", vbInformation, "ALERT: Missing Information"
Cancel = True
Exit Sub
End If
If ActiveSheet.Range("H2").Value = "" Then
MsgBox "Date Required", vbInformation, "ALERT: Missing Information"
Cancel = True
Exit Sub
End If
If ActiveSheet.Range("K2").Value = "" Then
MsgBox "Shift Required", vbInformation, "ALERT: Missing Information"
Cancel = True
Exit Sub
End If
If ActiveSheet.Range("M2").Value = "" Then
MsgBox "Line Required", vbInformation, "ALERT: Missing Information"
Cancel = True
Exit Sub
End If
Dim wbTime As Workbook
Set wbTime = ThisWorkbook
Dim wbData As Workbook
Dim LastRow As Long
Set wbTime = ActiveWorkbook
With wbTime.Sheets("Production Time Sheet")
LastRow = .Range("E" & .Rows.Count).End(xlUp).Row
End With
wbTime.Sheets("Production Time Sheet").Range("A6:R" & LastRow).Copy
Set wbData = Workbooks.Open("S:\Lean Carrollton Initiative\Michael\Time Sheet Data LT Test.xlsm")
Set wbData = ActiveWorkbook
wbData.Worksheets("Log").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
wbData.Close SaveChanges:=True
Dim Fname As String
Dim Path As String
Dim shft As String
Dim Line As String
Set wbTime = ActiveWorkbook
Fname = Sheets("Production Time Sheet").Range("I2").Text
shft = Sheets("Production Time Sheet").Range("Z9").Text
Line = Sheets("Production Time Sheet").Range("AC11").Text
Path = "K:\Groups\OFS Time Sheets\8hr Production Schedule\LT Jacketing\" & shft & Line & Fname & ".xlsx"
ActiveWorkbook.SaveAs filename:=Path, FileFormat:=xlNormal
End Sub
You are using as name of file the text 2/5/2019.xlsx. As far as I know, the simbol / cannot be used in Windows to name a file.
Try with a different name for file. Something like:
Fname = Replace(Sheets("Production Time Sheet").Range("I2").Text,"/","-")
a) Don't use Range.Text, use Range.Value2.
Text will give you exactly what is written in the cell, and if the cell diplays ###because your cell is to narrow to display a number, it will give you ###.
b) Put a statement Debug.print path before the SaveAs and check in the immediate window (Ctrl+G) if the path is exactly what you expect.
c) Be sure that when you issue the SaveAs-command, the same file is not already open in Excel - this happens often when you test your code repeatedly (it may still open from the last test). SaveAs saves a copy of the file and keeps it open!
d) Use FileFormat:=xlOpenXMLWorkbook when you name the file with extension xlsx. xlNormal will save the file with the old Excel file format and expects xls as extension.
e) Try to save the file with exactly the name from the Excel SaveAs dialog to see if the filename is okay and you have permission to save a file.

Receiving ActiveX Automation: Bad Index Error Message

Prelude
I am starting a new project, and basically I am using Excel as a log for another program I am using. With this being said, this is a mixture of VBA (Only when using Excel's object) and VB6 (the main "host" programming language). This is why both languages are tagged as I anticipate hateful comments from the use of tags; I am looking for a solution in either/mixture of both programming languages!!
Also, I am aware some VBA activists will say to never use ActiveSheet. I am not concerned about this and I would like to say thank you ahead of time. I have one sheet in this workbook as it's primary function is to serve as a log. The ActiveSheet will always be the one and only sheet.
I have the following code, and I am not too familiar with Setting a workbook as an object, which is likely the reason I receive the Bad Index error.
Sub Test()
' Checking if Excel is open, if not, open it.
Dim xL As Object, wBook As Object, iCloseThings As Byte
On Error Resume Next
Set xL = GetObject(, "Excel.Application")
On Error GoTo 0
If xL Is Nothing Then
iCloseThings = 1 ' Set Excel to close only if it was never open
Set xL = CreateObject("Excel.Application")
End If
Set wBook = xL.Workbooks("C:\Users\<UserName>\Documents\<WorkBook>.xlsx").ActiveSheet
If iCloseThings = 1 Then xL.Quit
End sub
What I need assistance with is how would I properly set this object to point to the exact workbook I have in the above example? All I have ever known to do was something such as Set wBook = XL.Workbooks("<WorkBook>.xlsx").ActiveSheet because I knew such workbook would already be open. But with the possibility of it not being open, I need something a little more flexible.
Thanks for your assistance!
you need some different cases handling, mainly depending if the wanted workbook is already open or not should a running Excel session be "caught"
you may want to use some dedicated Functions not to clutter your main code and be more effective in both debugging and maintaining your code, like follows
Option Explicit
Sub Test()
' Checking if Excel is open, if not, open it.
Dim xL As Object, wBook As Object, wSheet As Object, iCloseThings As Byte
Set xL = GetExcel(iCloseThings)
Set wBook = GetExcelWorkbook(xL, "C:\Users\<UserName>\Documents\<WorkBook>.xlsx")
If wBook Is Nothing Then Exit Sub
Set wSheet = wBook.ActiveSheet
If iCloseThings = 1 Then xL.Quit
End Sub
Function GetExcel(iCloseThings As Byte) As Object
On Error Resume Next
Set GetExcel = GetObject(, "Excel.Application")
On Error GoTo 0
If GetExcel Is Nothing Then
iCloseThings = 1 ' Set Excel to close only if it was never open
Set GetExcel = CreateObject("Excel.Application")
End If
End Function
Function GetExcelWorkbook(xL As Object, wbFullName As String) As Object
Dim wbName As String
wbName = Right(wbFullName, Len(wbFullName) - InStrRev(wbFullName, "\"))
On Error Resume Next
Set GetExcelWorkbook = xL.Workbooks(wbName)
On Error GoTo 0
If GetExcelWorkbook Is Nothing Then
Set GetExcelWorkbook = xL.Workbooks.Open(wbFullName)
Else
If GetExcelWorkbook.Path & "\" & wbName <> wbFullName Then
MsgBox "A workbook with the wanted name '" & wbName & "' is already open but its path doesn't match the required one" _
& vbCrLf & vbCrLf & "Close the already open workbook and run this macro again", vbCritical + vbInformation
Set GetExcelWorkbook = Nothing
Else
MsgBox "Wanted workbook is already open", vbInformation
End If
End If
End Function

EXCEL VBA to Open Word, Edit and Saveas in the specified location.

Am trying to Open the Word application, Edit, Saveas in the specified location and Need to check whether user has entered the correct Filename.
Here's my code
Dim Doc
Dim DocPath
Dim DocObj
Dim VarResult
DocPath = "C:\MyFolder\MyDocument.doc"
Set DocObj = CreateObject("word.Application")
Doc = DocObj.Documents.Open(DocPath)
DocObj.Visible = True
After opening the document I am doing some changes
With Doc.ActiveDocument
Set myRange = .Content
With myRange.Find
.Execute FindText:="FindText", ReplaceWith:="ReplaceText", Replace:=2
End With
End With
Now, I have an issue in saveas the file. I used both the alternative methods,
1: GetSaveAsFilename, 2: SaveAs. I need the saveas dialog box to appear(with all DefaultLocation, InitialFilename, DocumentType, Title properties). User needs to select and the same needed to be validated, whether user has not given Cancel button.
varResult = Doc.GetSaveAsFilename( _
FileFilter:="DP Document (*.doc), *.doc, DP Document (*.docx), *.docx", Title:="Save DP", initialvalue:="InitialDocument")
If varResult <> False Then
MsgBox "File choosen = " & varResult
Else
MsgBox "Please select the file"
End If
Am getting Run-time error. Thanks in advance.
According to this Microsoft Article, "If you use the CreateObject function with an object of type Word.Application or Word.Basic, the function fails if Word is already running." The failure is indicated by a Run-Time error. Microsoft suggests that you "check to see whether Word is already running. If it is not, start a new instance of Word." For example, you could use "the GetObject function to create a Word.Application object. If the GetObject function fails, Word is not running, so the CreateObject function is then used to set the Word.Application object." The code provided in the linked article is as follows:
Sub RunWord()
Dim wObj As Word.Application
On Error Resume Next
' Get existing instance of Word if it exists.
Set wObj = GetObject(, "Word.Application")
If Err <> 0 Then
' If GetObject fails, then use CreateObject instead.
Set wObj = CreateObject("Word.Application")
End If
' Add a new document.
wObj.Documents.Add
' Exit Word.
wObj.Quit
' Clear object memory.
Set wObj = Nothing
End Sub

Check if pptx and xlsx files are already open before attempt to open it

I guess this is a easy one but since I'm very new in VBA I can't figure it out.
I have this peace of code which opens a Power Point presentation and a Excel spreadsheet. dir_pptx and dir_xlsx are the respective filepaths.
Set ObjPPT = CreateObject("PowerPoint.Application")
Set ObjPresentation = ObjPPT.Presentations.Open("" & dir_pptx & "")
Workbooks.Open Filename:=dir_xlsx
My question: how to modify this code for check if the files are already opened and, if they are, don't open it again?
Sub wbcheck()
For Each B In Application.Workbooks
If B.name = dir_xlsx Then
MsgBox B.name & " already open"
'exit sub or some other handler
Else
Workbooks.Open Filename:=dir_xlsx
End If
Next
End Sub

Resources