Check if an Add-in is installed and running VBA - excel

I am trying to check if an add-in is installed and running. I am using this piece of code:
On Error Resume Next:
Set SolverNome1 = AddIns("Solver Add-In") 'Solver may have two different names
Set SolverNome2 = AddIns("Solver")
MsgBox IsEmpty(SolverNome1)
MsgBox IsEmpty(SolverNome2)
If IsEmpty(SolverNome1) And IsEmpty(SolverNome2) Then
MsgBox "Install Solver add-in before trying to install this add-in.", vbExclamation
Application.myAddInName.Installed = False 'uninstall my add-in
End If
The problem is that even with the Solver Uninstalled I still get IsEmpty(SolverNome1) = false so my condition clause doesn't work as desired. I guess there I am misunderstanding the concept of installed or not. What piece of code should I be using to check if solver is running?

Answering my on question:
It is necessary to access the .installed property like this:
myBoolean1 = SolverNome1.Installed 'will return false because the add-in is set and not installed
myBoolean2 = SolverNome1.Installed 'won't return because add-in is not set

Related

Macro won't run in my latest system(capturing data)

I have 2 macro version code that runs in old version of PCOMM System(capturing data). However After the update of latest PCOMM System(Capturing data). My macro will run as "Macro run complete" but the data didn't reflect in excel.
Here's my Version 1 My code can't capture data in my new latest PCOMM system(capturing data site) However macro says "Macro Run Complete!" to get the data. Show images and sample code below
Public Function Extra_Init() As Boolean On Error
GoTo ExitExtraInit
Extra_Init = False
Set goExtraSys = CreateObject("PCOMM.autECLConnList")
goExtraSys.Refresh
Set goSessions = CreateObject("PCOMM.autECLOIA")
goSessions.SetConnectionByHandle (goExtraSys(1).Handle)
giSessionCount = goExtraSys.Count
If giSessionCount = 1 Then
Set goSession = CreateObject("PCOMM.autECLPS")
goSession.SetConnectionByHandle (goExtraSys(1).Handle)
If goSession.CommStarted Then
Extra_Init = True
Else
Extra_Init = False
End If
End If
Exit Function
Here's my Version 2 My Microsoft Visual Basic when being run, an error prompts showing "class not registered"
Sample images below.
Error appears in this part of code.
Set Exl = GetObject(, "Excel.Application")
Set Extra = CreateObject("PCOMM.autECLConnList")
Extra.Refresh
Thank you in advance!
Get the data in my latest version of PCOMM System

What about "Application" as default object in Excel VBA?

I have just written this easy macro in Excel VBA for merging a group of selected cells:
Sub Macro_Merge()
Dim Temp As String
Dim S As Variant
Temp = ""
For Each S In Selection
If Temp = "" Then
Temp = CStr(S.Value)
Else:
Temp = Temp + "," + CStr(S.Value)
End If
Next
Selection.Merge
Selection.Value = Temp
Selection.VerticalAlignment = xlTop
End Sub
This works fine, but I always see that annoying dialog box, warning me about loosing data while merging (which is exactly what I'm trying to avoid in my macro).
I can get rid of that dialog box, configuration the Application's DisplayAlerts property:
Application.DisplayAlerts = False
Selection.Merge
Selection.Value = Temp
Application.DisplayAlerts = True
This is working fine.
So, as Application is the default object, I tried to clean up my code, as follows:
DisplayAlerts = False
Selection.Merge
Selection.Value = Temp
DisplayAlerts = True
As you see, I simply omit mentioning the Application object. This is something which is allowed and I've done in the past. (If not in VBA, then Delphi, maybe?)
... but to my surprise, the dialog box appears again (although pressing F1 brings me to the official "Application.DisplayAlerts" documentation).
This leaves me with a simple question:
If a simple DisplayAlerts = ... does not equal Application.DisplayAlerts = ... anymore, what does it mean and how can I use it?
For your information, I'm working with Excel-365.
DisplayAlerts is an undeclared variable.
Certain Application properties and methods can (effectively) have the Application omitted:
ActiveCell, ActiveSheet, ActiveWorkbook, ActiveWindow, Addins, Charts, Selection, etc.
Calculate, Evaluate, Intersect, Run, Union, etc.
(but see this answer why/how this works):
A boolean property such as DisplayAlerts (EnableEvents, ScreenUpdating, etc) doesn't fall into the above category.
A golden rule in order not to fall into such a trap is the usage of Option Explicit while writing macros.
Just to add some information to the answer of #BigBen. If you write something like Workbooks or ActiveSheet in your code, VBA is not looking into the Application-object - it is looking into a (rather well hidden) object named Global.
The global object is exposing some (but not all) properties and methods of the Application-object, so ActiveSheet is referring to Application.ActiveSheet - but not because the Application has a member with this name but because the Global object defines that ActiveSheet means Application.ActiveSheet. In fact even the Application-object is accessed via the Global object.
There is hardly any information about this Global object or its concept. I found a page from Microsoft describing the Global object of MS Word, but the only explanation there is "Contains top-level properties and methods that don't need to be preceded by the Application property.". For Excel, I found this page on O'Reilly.
From time to time you get strange error messages like "Excel VBA Method 'Range' of object'_global' failed" - this is a pointer to the Global object. I would be glad to learn more about the concepts and mechanics of this object, but I am afraid that there are only very few people around that know more (except of course Mathieu Guindon AKA Mr. Rubberduck...). In daily life, we take it for granted that things like ActiveSheet simply works.

Excel 2011 for Mac: Compile error on line that should not be compiling

I am creating an Excel Macro-Enabled Workbook for both Windows & Mac. One platform on the Mac I want it to run on is Excel 2011.
My workbook uses a custom Ribbon tab. Sometimes, depending on what the user does, I want the text of the ribbon buttons to change. So I have code that does this.
I know that a custom Ribbon tab is not possible in Excel 2011. That is okay. However, there is a line in my code that is giving me a compile error on that version of Excel. I thought I had it set that it would not compile the code if running on this version of Excel, but it doesn't seem to be working.
I am defining a variable of type IRibbonUI for use inside a standard module. (The module is Module3, and it is dedicated to code having to do with the Ribbon.) I wrap the variable definition code (along with the rest of the code in this module) in an #IF statement, like so:
#If Not Mac or MAC_OFFICE_VERSION >=15 Then
Dim ribbonUI As IRibbonUI
... rest of the code in Module3 ...
#End If
This means it should not compile at run-time on Excel 2011.
When the workbook opens, I do not get any errors. However, when I am running a sub (let's call it "UpdateOptions", and it is in Module1) that calls a sub that changes the Ribbon (let's call that one "ChangeRibbon", which is in Module3*), I get a compile error on the ribbonUI line: User-defined type not defined
I don't understand why, because as far as I understand, the code in that module shouldn't be compiling at run-time.
*ChangeRibbon should never actually be run on Excel 2011. I have an IF statement that makes sure it is not, like so:
Sub UpdateOptions()
... some code ...
#If Not Mac or MAC_OFFICE_VERSION >=15 Then
Module3.ChangeRibbon
End If
... some other code ...
End Sub
When I step through the code, the error happens when UpdateOptions is first called by another sub. The step-through highlights the name of the sub as the line that is causing the error:
Sub UpdateOptions()
Does anyone know why this is happening? It doesn't make any sense to me.
I'll post it as an answer since it won't fit into the comment section.
It seems that you enter your code, even thought it should not. The easiest explanation is, that your if statement is not evaluated properly. You should check the values of Mac and MAC_OFFICE_VERSION, this should already show you what went wrong. Another reason could be that you made a wrong assumption about how VBA evaluates logic clauses: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/operator-precedence
If you split/nest the the If-Block it is easier to see which evaluation goes wrong:
Public Sub testVer()
#If Not Mac Then
Debug.Print "Not a Mac"
#Else
#If MAC_OFFICE_VERSION >= 15 Then
Debug.Print "Mac Version equal or above 15: ", MAC_OFFICE_VERSION
#Else
Debug.Print "Mac Version below 15: ", MAC_OFFICE_VERSION
#End If
#End If
End Sub
Here is a small example to see how your if clause gets evaluated:
In VBA the clause Not A Or B is the same as (Not A) Or B, so maybe you just mixed up logic.
Sub testOrNot()
printNotAOrB True, True
printNotAOrB True, False
printNotAOrB False, True
printNotAOrB False, False
End Sub
Private Sub printNotAOrB(A As Boolean, B As Boolean)
Debug.Print "A = " & A, "B = " & B
Debug.Print "Not A Or B :", Not A Or B
Debug.Print "Not (A Or B):", Not (A Or B)
Debug.Print "(Not A) Or B:", (Not A) Or B
Debug.Print
End Sub
I had the thought of if I could possibly "fake out" Excel 2011 into thinking I had created a custom data type for IRibbonUI (and, as it turned out, I had to do it for another type, too) and that worked. In my module dealing with all my Ribbon code, I put this at the top:
#If Mac And MAC_OFFICE_VERSION < 15 Then
Type IRibbonUI
ribbontype As String
End Type
Type IRibbonControl
ribboncontrol As String
End Type
#End If
I no longer receive the compile error.
In regards to L8n's answer, I don't believe the logic of the IF statement was a problem. I had also tried calling on a Function I created long ago to test if the version of Excel was Excel 2011 for Mac. So my IF statement started like this:
#IF ExcelForMac2011 = False Then
I know my function works properly, because I call it many other times in my workbook, and it has always worked correctly. So I don't think it was a logic problem in the IF statement. I think this was a bug in Excel 2011. Unfortunately, it has MANY, MANY bugs.

'Type Mismatch' Error on ADODB.Recordset

I have a program that is supposed to read data from an SQL database and report back to Excel. It works as expected on a 32-bit machine, but since I moved over to a 64-bit work environment, the program has failed to run. Here is a sample of my code (the first error returned):
Private Sub SearchBox_Change()
ResultBox.Clear
Call CompileQuery
'If the query is empty
If SearchBox.Value = "" Then
NumShowingLabel = "Showing 0 of 0 Results"
ResultBox.Clear
GoTo noSearch
End If
'Open a new query with varQuery
With varRecordset
.ActiveConnection = varConnection
.Open varQuery
End With
'Set NumShowingLabel
If varRecordset.RecordCount > varMaxResults Then
NumShowingLabel = "Showing 60 of " & varRecordset.RecordCount & " Results"
Else
NumShowingLabel = "Showing " & varRecordset.RecordCount & " of " & varRecordset.RecordCount & " Results"
End If
'As long as there is a record, move to the first one
If Not varRecordset.RecordCount = 0 Then varRecordset.MoveFirst
'Add each record to ResultBox
If varRecordset.RecordCount > varMaxResults Then
For varTempInt = 1 To varMaxResults
ResultBox.AddItem varRecordset.Fields("FileName").Value
varRecordset.MoveNext
Next
Else
For varTempInt = 1 To varRecordset.RecordCount
ResultBox.AddItem varRecordset.Fields("FileName").Value
varRecordset.MoveNext
Next
End If
'Release varRecordSet
varRecordset.Close
noSearch:
End Sub
When run, Excel returns an error "Type Mismatch" and highlights .RecordCount of For varTempInt = 1 To varRecordset.RecordCount (the last for loop in the sample). I have installed the hotfix recommended by the Windows Support Article 983246, at least to the best of my understanding. I installed it to the C: directory and restarted my machine, but it still does not work.
Edit 1: Just wanted to clarify that I was previously using ADO 2.5 NOT ADO 6.1
TL;DR: How can I fix a RecordSet.RecordCount "Type Mismatch" error on a 64-bit machine running Excel 2010?
this issue is actually caused by a bug in earlier excels. there is a hotfix out there. HotFix
I develop some macros on office 16, but when I do UAT on previous versions, it fails, a quick easy solution for this is simply to cast the RecordCount
rst = SomeRecordset
dim rstCount as Long
rstCount = CLng(rst.RecordCount)
Thank you guys for your quick replies, however, I somehow managed to get the idea of using ADO 6.1 instead of ADO 2.5. It appears that using a more up-to-date version of ActiveX Database Objects did the trick, duh.
For future reference, if you are going to upgrade to ADO 6.0, the ConnectionString value will be the same EXCEPT you must use User ID=<USR>; Password=<PSWD> instead of USR=<USR>;PWD=<PWD>
I change it from
as Long
to
as LongLong
Then my VBA starts to work. No hotfix needed...
I haven't had this exact problem, but I've found that the recordcount property on an ADODB recordset is hit or miss. Your best bet is to rewrite the loops like:
recordset.movefirst
While Not recordset.eof
<your stuff with your record>
recordset.movenext
Loop
Also, to test that there are records in your recordset you can use:
If recordset.BOF and recordset.EOF THEN
<Something is wrong there are no records>
End If
My guess is that the ADODB recordcount property is probably crap with the 64 bit version of whatever ODBC driver you are using as it is in nearly every ODBC driver.
We had this error due to the same type of comparison and used the same sort of answer as from dfresh22 and Jonson Tsai. Thanks folks!
The only difference for us was that the error was occurring on 64-bit Office and we still have several users on 32-bit Office so it was easier to convert down to the smaller 32-bit variable instead of up to the larger 64-bit variable. Since the variable we were comparing against RecordCount will always be less than 100 (and definitely always < 32K) I was able to just Convert from Long to Integer in the 64-bit version and 32-bit code would just convert from Integer to Integer:
IF intNumRecs > CInt(DBreports.RecordCount) THEN...
Just check the version of Excel. ADO works well 32 bit and teething issues with 64 bit.

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