OLE Excel object manipulation causes run-time error '91' - excel

I am maintaining an application that was written in Visual Basic 6.0 and makes use of the several OLE controls with Excel.Sheet.8 class objects. Several users are getting the following error when they reach a point in code that attempts to manipulate the excel objects.
Run-time error '91': Object variable or With block variable not set
Below are examples of the code that trigger this error. I believe that the issue happens at:
Set oExcel = oleXl.object
Here are the points in the code where it happens:
Private Sub Form_Load()
Dim i As Integer
Dim j As Integer
Dim sTempStringA As String
Dim sTempStringB As String
'Set up excel sheet
centerform Me
Set oOutGrid = oleXlOutput.object
...
Private Sub Form_Load()
centerform Me
Set oOtherFx = oleXlFx.object
...
Private Sub Form_Load()
Dim iRet As Integer
Dim i As Integer
On Error GoTo Err_Handler
centerform Me
Call InitArray
Me.Caption = "TJUJ | Version " & version & " | Enter Custom Fx"
Set oBook = oleExcel.object
...
Is there a specific situation or environment in which this error would be generated from this line of code OR a way that I can ensure the object will always be accessible at this point in the code?
The error only happens occasionally, and I can't reproduce it on my developer machine at all. I also do not have access to the machines that it is happening on, but it seems to be encountered when there is an instance of the EXCEL.EXE process running.

When you get runtime-error 91, you can bet there's an uninitialized object somewhere in the statement. In other words, you are trying to use the properties or methods of a variable/object with a value of Nothing.
In your examples, oleXl, oleXlFx, and oleExcel are probably Nothing. So when you refer to their .object property, you trigger the RTE.
Somewhere in your code these variables have to be initialized to something. Look for statements like Set oleXl = CreateObject("Excel.Application") or Set oleXl = New Excel.Application
One suggestion; when you find the statements that actually initialize those OLE objects, check to see how the error-handling is coded. If you see things like this:
On Error Resume Next
Set oleXl = CreateObject(...
add a test to make sure the object was instantiated
On Error Resume Next
Set oleXl = CreateObject(...
If oleXl Is Nothing Then
MsgBox "Hey, my object is Nothing!"
End If

Microsoft suggests that we can fix error 91 by creating a new registry key. To create a new key follow the steps below.
Click on the Windows Start menu
Type Regedit in the search box
Press Enter
Locate the following entry in the registry. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Transaction Server
Now select the transaction server and right click on it
Select New and then choose Key
Name the key as Debug
Right click on the Debug key and choose New
Now select Key and name the key as RunWithoutContext
Ref: http://backspacetab.com/error-91/

Related

Automate the pcomm login from Excel vba

I am trying to automate my PCOMM login process. When I execute the below piece of code, I am getting an error.
Dim Num as Long
Set autECLConnList=
CreateObject("PCOMM.autECLConnList")
autECLConnList.Refresh
The error I got is "ActiveX component can't create object." in line 2. I even checked whether the dll was missing, but it looks fine.
According to the documentation, it appears you need to create the object before initializing it:
Dim autECLConnList as Object
See here: https://www.ibm.com/support/knowledgecenter/en/SSEQ5Y_13.0.0/com.ibm.pcomm.doc/books/html/host_access08.htm
Dim autECLConnList as Object
Dim Num as Long
Set autECLConnList = CreateObject("PCOMM.autECLConnList")
autECLConnList.Refresh
Num = autECLConnList.Count
Num is the number of connections present in the autECLConnList collection for the last call to the Refresh method and The Count property is a Long data type and is read-only.

vb6 trying to get old program working with excel 2013

I have this code from a program that was created to take data and export it into excel it is in vb6 and I dont know much about vb6 I started coding in vb.net could someone tell me why this isnt working with excel 2013 it opens but then closes right away and i am unsure as to why.
Sub GetExcel()
Dim MyExcel As Object ' Variable to hold reference
' to Microsoft Word.
Dim ExcelWasNotRunning As Boolean ' Flag for final release.
' Test to see if there is a copy of Microsoft Excel already running.
10 On Error Resume Next ' Defer error trapping.
' Getobject function called without the first argument returns a
' reference to an instance of the application. If the application isn't
' running, an error occurs.
20 Set MyExcel = GetObject(, "XLMAIN")
30 If Err.Number <> 0 Then ExcelWasNotRunning = True
40 Err.Clear ' Clear Err object in case error occurred.
' Check for Microsoft Excel. If Microsoft Excel is running,
' enter it into the Running Object table.
50 DetectExcel
' Set the object variable to reference the file you want to see.
60 Set MyExcel = GetObject(App.Path & "\test.xls")
' Show Microsoft Word through its Application property. Then
' show the actual window containing the file using the Windows
' collection of the MyWord object reference.
' MyExcel.Application.Visible = True
' MyExcel.document(1).Visible = True
70 MyExcel.Show , f1
'//////////////////////////////////////////////
' Do manipulations of your file here.
'//////////////////////////////////////////////
' ...
' If this copy of Microsoft Excel was not running when you
' started, close it using the Application property's Quit method.
' Note that when you try to quit Microsoft Excel, the
' title bar blinks and a message is displayed asking if you
' want to save any loaded files.
80 If ExcelWasNotRunning = True Then
90 MyExcel.Application.Quit
100 End If
110 Set MyExcel = Nothing ' Release reference to the
' application and spreadsheet.
End Sub
Sub DetectExcel()
' Procedure dectects a running Word and registers it.
Const WM_USER = 1024
Dim hwnd As Long
' If Excel is running this API call returns its handle.
10 hwnd = FindWindow("XLMAIN", 0)
20 If hwnd = 0 Then ' 0 means Word not running.
30 Exit Sub
40 Else
' Word is running so use the SendMessage API
' function to enter it in the Running Object Table.
50 SendMessage hwnd, WM_USER + 18, 0, 0
60 End If
End Sub
even if i can get some direction on how to rewrite this it would be appreciated.
It's been a long time since I've used it, so you may need to address some of the finer points... But:
First and foremost - get rid of the On Error Resume Next it masks whatever happens next.
This is not a situation where you want to have errors ignored. Capture the error, show something useful (not debug information and not details that can be used for hacking) to the user, and resume or return (after cleanup of assigned object variables to avoid memory leaks).
Then step through the code to see what errors you get.
Some of the things that may help:
Change the specification in your GetObject to be "Excel.Application" i.e.
Set MyExcel = GetObject(, "Excel.Application")
Instead of MyExcel.Show which may or may not be supported, use actual Excel objects and their methods and properties, for instance the commented MyExcel.Application.Visible = True works, while I question the MyExcel.document(1).Visible = True.
Look up the Excel object model help for details. And never hardcode the index - obtain the actual reference that you want and use it.
You can still find articles about Excel and VB6 on line. Use your search engine of choice and good luck.
Beware of those who say something is impossible - first see if it works. Some say you can's install VB6 on a 64-bit system - that is not true, but there are some issues getting it to work. Some say you can't interact with 64-bit Office from VB6, but that is not true. Maybe you can't do some things - I haven't done much with it, just enough to know it is possible to do some things.
Consider developing and testing with typed objects in VB6. It can be very helpful, but to make the application version independent, you will need to remove the object typing before final test and deployment.

Object required error when clicking command button

I'm receiving an "Object required" error when trying to access my user form. It highlights the following code:
Sub DataEntry()
ServiceUpgradesDatEntry.Show
End Sub
I've double checked that the name is correct. I'm still new to VBA so any help would be greatly appreciated!
Go to Tools - Options - General in the VBE and change Error Trapping to Break in Class Module. There is an error in the userform's Initialize event, but the VBE isn't set to break in the userform's class module so it breaks on the line that sent you into the class module (the .Show line).
Once you've set that, clicking Debug on the error will highlight the line that's actually producing the error.
Treat your userform like an object and declare and instantiate it accordingly.
Public Sub DataEntry()
Dim dataEntryForm As ServiceUpgradesDatEntry
' Create an instance of the form
Set dataEntryForm = New ServiceUpgradesDatEntry
' Show the form
dataEntryForm.Show
' If the form was opened as Modal, then the code here will only run
' once the form has been hidden/closed
' Now destroy the object
Set dataEntryForm = Nothing
End Sub

Excel VBA Missing Reference - PI Osisoft

I have an VBA code where I use many objects from PISDK, which I have to add as reference to my project.
I must explicitly declare the variables otherwise the code won't work. I don't know why. Excel throws an error ("types doesn't match") if I declare, for example, pt as object instead of PIPoint.
Here is part of my code:
Dim srv As Server
Dim pt As PIPoint
Dim pv As PIValue
Dim dt As New PITimeFormat
The problem is: when user doesn't have this reference installed, Excel gives me an compilation error, so it's impossible to catch and handle this error. Since this code runs on a user-defined function, as soon as the user opens the workbook, he gets stuck with compiling errors.
I must be able to catch this error.
I can't find documentations to fully implement late binding on this code. I don't know if it's really possible to do it. I know it could solve my problem.
Also, I know I could check if the reference is installed, thru:
thisworkbook.vbproject.references
But if the user doesn't allow access to the vbaProject object under Excel options, I am not able to do this.
Any idea?
I managed to solve my problem declaring everything as object and then using createobject afterwards.
The main problem doing this was using functions, like this one:
I have the function "arcValue". It takes three arguments:
arcValue(TimeStamp as PITimeFormat, Mode as RetrievelTypeConstants, Optional asynchStatus as PIAyncnStatus)
The way I use it doing early binding is:
dim pt as PIPoint
dim pv as PIValue
set pv = pt.data.arcValue("01/09/2014 17:00:00", rtInterpolated)
This works. But when I do:
Dim myPISDK As Object
Dim srv As Object
Dim pt As Object
Dim pd as Object
Dim pv as Object
Set myPISDK = CreateObject("PISDK.PISDK")
Set pv = CreateObject("PISDK.PIValue")
Set srv = myPISDK.Servers.defaultserver
Set pd = pt.DATA
Set pt = srv.PIPoints("piTAG")
Set pv = pd.ArcValue("01/09/2014 17:00:00", rtInterpolated)
It doesn't work. But why?
There were two problems:
First: When I use late binding (createobject) I don't have access to "rtInterpolated" constant, so I have to use its equivalent number.
Set pv = pd.ArcValue("01/09/2014 17:00:00", 3)
But this still doesn't work. So I had to do this to make it work:
Set pv = pd.ArcValue("01/09/2014 17:00:00", 3, Nothing)
And then everything started working. I don't know why, but VBA makes me write something do all parameters, even if they are optional.
This way, I am able to detect erros in runtime, so I used this code:
If myPISDK Is Nothing Then
piVerified = "Erro PI"
Exit Function
End If
Also, I had to remove all references (they are not used anymore, anyway) because it was causing malfunction on other parts of my code not related to this one when the references were missing.
You can use something like that:
Sub NotUsed()
Dim pt As PIPoint
End Sub
Function ReferenceCheck() As Boolean
On Error GoTo NoRef
pt = Acrobat.AV_DOC_VIEW ' PIPoint
ReferenceCheck = True
Exit Function
NoRef:
ReferenceCheck = False
End Function
Sub Test()
If ReferenceCheck Then NotUsed
End Sub
The function refer to a proprieties of the object. If the reference it's ok return true otherwise false.
In the phase of init you can check like that.
The sub NotUsed, don't create Error because not called...
In my sample I use the ADOBE Object ...

ADODB.Connection undefined

Reference Excel VBA to SQL Server without SSIS
After I got the above working, I copied all the global variables/constants from the routine, which included
Const CS As String = "Driver={SQL Server};" _
& "Server=****;" _
& "Database=****;" _
& "UID=****;" _
& "PWD=****"
Dim DB_Conn As ADODB.Connection
Dim Command As ADODB.Command
Dim DB_Status As Stringinto a similar module in another spreadsheet. I also copied into the same module
Sub Connect_To_Lockbox()
If DB_Status <> "Open" Then
Set DB_Conn = New Connection
DB_Conn.ConnectionString = CS
DB_Conn.Open ' problem!
DB_Status = "Open"
End If
End SubI added the same reference (ADO 2.8)
The first spreadsheet still works; the seccond at DB_Conn.Open pops up "Run-time error '-214767259 (80004005)': [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
Removing the references on both, saving files, re-opening, re-adding the references doesn't help. The one still works and the other gets the error.
?!?
I observed the same error message and in my case nothing had changed. I wondered if my odbc driver needed to be reinstalled (based on what i read online). In any case, restarting excel did the trick. Sometimes the solution is much simpler. :-)
When the error pops up, check your "locals" windows to see what the CS holds. View > Locals Window
Problem: Your constant isn't found by the compiler.
Solution: With the constant being located in a separate module, you'll need to set it as Public for the other code to see it.
Proof:
In order to prove this theory you can do the following:
Open a new Excel spreadsheet
Go to the VBA designer and add a new module
In this module put:
Const TestString As String = "Test String"
Then add the following code to ThisWorkbook:
Public Sub TestString()
MsgBox (TestString)
End Sub
After adding this return to the workbook and add a button, selecting "TestString" as the macro to run when clicked.
Click the button and a blank message box will appear.
Go back to the VBA designer and change the const in Module1 to Public
Click the button on the spreadsheet and you should now see "Test String" in the message box.
I realize that this question is really old. But for the record I want to document my solutions for the error here: It was a data related error in a spreadsheet! A column was formatted as date and contained a value 3000000. Changing the Format to numbers solved the Error 80004005.

Resources