Why doesn't VBE.ActiveCodePane.CodeModule work when the VBE (code window) isn't open? - vba

Create a form that runs the following code.
MsgBox (VBE.ActiveCodePane.CodeModule)
And this message appears.
Now save, close, and reopen the database, and see this message:
Run-time error '91': Object variable or With block variable not set
If you open the Visual Basic Editor, it runs again. Even if you close the VBE, it still runs.
But when you close the whole application and reopen it, leaving the VBE closed, you get the error.
Why? What's going on here?

You reference the active pane object. The object isn't set until a pane gets activated. So before you open the VBE, the object is not set yet. Once you close the VBE, the object remains, so you can still reference it.
To get a handle to the ActiveCodepane object, without opening the VBE, is by activating a VBComponent, like this:
VBE.ActiveVBProject.VBComponents("Module1").Activate
You can activate any VBComponent like this.

Well when the VBE is closed upon the first opening of the application, there is no ActiveCodePane, you can check this in a conditional upon loading your form:
If (Application.VBE.ActiveCodePane Is Nothing) Then MsgBox "ActiveCodePane is Nothing"
The VBE exists and properties and methods can be used, but there is no ActiveCodePane which is why you're receiving the null reference exception. Just opening the VBE will still produce your error if you closed all CodePanes before saving and closing previously (unless a module exists for some reason). You must the explicitly open a CodePane, to set the 'ActiveCodePane' property.
This makes sense. What is it that you're trying to access via the ActiveCodePane property? Perhaps I can help find a way around?
Edit
Presumably, as you develop this Form and associated Modules, you'll know what they're called, and would be able to use a different method than the ActiveCodePane, such as that which #Bas Verlaat mentioned. Alternatively, you can loop through each code pane in the active VBProject and try and match on a name or something:
Option Compare Database
Option Explicit
Private vbProj As VBIDE.VBProject
Private vbComp As VBIDE.VBComponent
Private vbMod As VBIDE.CodeModule
Private Sub Command0_Click()
Set vbProj = Application.VBE.ActiveVBProject
For Each vbComp In vbProj.VBComponents
MsgBox vbComp.CodeModule
Next
End Sub

As Bas Verlaat said, before you open the VBE, the object is not set yet.
Obviously the VBE won't be open when a user is using the program. Referencing the Active Code Pane should only be done when developing and debugging, and never in production.
For example the following custom made error message is great for debugging, but will fail if deployed to production.
ErrorHandler:
MsgBox "Error " & Err.number & ": " & Err.Description & " in " & _
VBE.ActiveCodePane.CodeModule, vbOKOnly, "Error"

Approach
Since sometimes it can't be avoided to use VBE functionality, the general solution for me is this ...
make sure to initialize/activate the relevant workbooks VB project (components)
make sure to initialize/activate other workbooks VB projects (components) after they are opened (if their VBE properties/code may be relevant later in the process)
VbeInit usage
To do this one could call (see code below)
VbeInit in the beginning of some event (e.g. the Workbook_Open() event) and
VbeInit someOpenedWorkbook whenever a relevant workbook was just opened (e.g. using Workbooks.Open(...))
Example Case
It works for the simpler above case.
A more complex case, where this is very obvious and necessary, is when you rely on the CodeName of sheets in workbooks. E.g.
if the user is allowed to reName some sheets, but they should still be uniquely identifiable by the VB application, via their CodeName and
such sheets (e.g. serving as template sheets) are copied (sheet.Copy ...) to other workbooks.
Then the sheets CodeName will only be copied, if the sheets VBComponent has been activated (e.g. via myVBComponent.Activate or opening the source-sheet-containing workbook in the VBE).
The VbeInit procedure
Procedure VbeInit(Optional wb As Workbook)
With Application.VBE
Dim pj As VBProject: For Each pj In .VBProjects
'ignore unsaved (=> fully initialized) workbooks
If Not wb Is Nothing Then If wb.FullName <> VBProjFilename(pj) Then GoTo continue
Dim c As VBComponent: For Each c In pj.VBComponents
c.Activate
Next c
continue:
Next pj
End With
End Procedure
Function VBProjFilename(pj As VBProject) As String
On Error Resume Next 'leave result empty if workbook (code) not saved yet
VBProjFilename = pj.Filename
End Function

Related

VBA - excel closes the previous workbook on opening the new one

I have a strange problem, I suscpect it's connected to the version of the Excel, but I'm not sure at all. I can't figure it out alone so I need your help. I have a macro, which operates on a fresh workbook - it's not saved anywhere, as the worker will save it manually afterwards. The macro is a .xlam format add-in, adding a couple of buttons to the ribbon and these buttons start the code.
Inside the code I have simple lines for opening a new workbook, chosen earlier by an user:
Application.DisplayAlerts = False
Set wbMPA = Workbooks.Open(MPA_file)
Application.DisplayAlerts = True
Earlier, the code sets active workbook as an object/workbook the macro will mainly work on (tried both versions):
Set dwb = Application.ActiveWorkbook
and later in the code
dwb.activate
OR:
dwb = ActiveWorkbook.Name
and then
workbooks(dwb).Activate
The lines are in separate subs, but the variable is globally declared.
The code works fine until the opening of wbMPA (watching it in the locals all the time). When I try to open the new file with the code above, the earlier workbook (dwb) just closes itself from unknown reasons.
The error I get from the 1st method is this:
error screenshot
The second one gives a simple "Subscipt out of range".
The errors, however, are not a problem. The problem is the cause of them, which is closing of the workbook from unknown reasons.
It happens only when I open the completely new workbook (using the excel icon on the Start bar) - when I do it from File -> New -> Blank Workbook using already opened workbook, the error does not occur.
Another strange thing - me and my colleague from work use 2013 version of Excel. I never have this error, she has it every time.
This is a general scheme of the code, other things are meaningless in this case because there are no other manipulations of workbooks/worksheets.
Dim dwb As Object
Dim wbMPA As Object
Sub_1()
Set dwb = ActiveWorkbook
Set wbMPA = Workbooks.Open(MPA_file)
Call Sub_2
End Sub
Sub_2()
dwb.Activate
End Sub
I get an error on the activation of dwb in Sub_2, because it closes itself for God knows what the reason on the opening of wbMPA in the Sub_1.
If you have only opened a blank workbook (clicking Excel from Toolbar, for example) and then you open any named workbook before making any changes to the blank workbook, the blank workbook will disappear. I believe that is normal/expected behavior.
I can't speculate why this happens on one computer but not another, but this is always how I have observed new/blank documents (Excel, PowerPoint, Word) to behave, and assume this to be the normal behavior. You may have some different option/configuration on your Excel environment which is changing this default behavior, or maybe you are slightly altering the blank file before running the macro, and your co-worker isn't, etc.
A word of caution to avoid relying on ActiveWorkbook -- and especially in this case if the expectation is to always Set dwb to a new/blank workbook, the best way to do that is to explicitly create a new/blank workbook, rather than relying on the user to manually open a new/blank target workbook.
Set dwb = Workbooks.Add
If, on the other hand dwb must be assigned to some other known/existing workbook, then you should be either providing the file path to an Open statement, or the workbook name to the Workbooks collection.
On a related note, it's almost never necessary to Activate a workbook, see here:
How to avoid using Select in Excel VBA macros
And further note: your variables aren't globally scoped, they're scoped only to the module using Dim statement. A public declaration uses the Public keyword, not the Dim keyword. Both module-scoped and global-scoped should be used with caution (Public moreso than module-scoped) and in most cases it's preferable to pass objects/variables by reference to dependent subs and functions:
How to make Excel VBA variables available to multiple macros?

VBA Global variables no longer declared after deleting worksheet

I have some public worksheet variables that are first initialized when the workbook is open. I have a button that does this essentially:
Dim Response As Variant
Response = MsgBox("Are you sure you want to delete this worksheet?", vbYesNo + vbExclamation, "Confirm Action")
If Response = vbNo Then
GoTo exit sub
End If
'Save workbook prior to deletion as a precaution
ThisWorkbook.Save
ActiveSheet.Delete
For some reason after this runs, those worksheet variables are no longer declared and I have to reinitialize them every time. I tried adding my InitVariables macro call after the .Delete and it still doesn't work.
Any reason why this might be happening?
The reason is actually really simple - a Worksheet is a class in VBA, and its code module gets compiled along with the rest of your project even if it's empty. When you delete a worksheet and let code execution stop, the next time you run some code the VBE has to recompile the project because you removed a code module. That causes your custom class extensions to lose their state.
Note that this does not happen unless the code stops running and is recompiled. This works just fine:
Sheet1.foo = 42 'foo is a public variable in Sheet1
Sheet2.Delete
Debug.Print Sheet1.foo 'Prints 42
I just tested it using Comintern foo. It's interesting that the standard module foo losses it value but the public foo variable in a worksheet module does not loses it's value.

Excel 2013 to 2010 backward compatibility issue with ActiveX (NOT Dec14th update issue)

I am transitioning a set of interrelated Excel documents that use VBA code for lookups, data manipulation and calculations from Excel 2010 to Excel 365. I have both on my development machine, however these get sent (via email) to customers all over and then returned. I use .xlmb file formats for the file size savings however this doesn't seem to be affecting the outcome.
CURRENT ISSUE
When I save a workbook using 365 on my development machine, users get errors when performing an action that runs my VBA code when run from a machine that only has 2010 installed (if both versions are installed, the behavior does not seem to happen). I have focused the problem to when there is code in a module and there is an ActiveX control on a sheet. ONLY this combination seems to create the issue.
The test file/code I've created that consistently shows the issue is a workbook with the following code in a module:
Dim strBook As String
' Worksheet Names
Public Const wksTest = "Sheet1"
Public Function TestMe(PassedSheet As String)
strBook = ActiveWorkbook.Name
Workbooks(strBook).Worksheets(PassedSheet).Protect
Workbooks(strBook).Worksheets(PassedSheet).Unprotect
MsgBox "Worked from function", vbOKOnly, "Response"
End Function
And code in the sheet. It works with this code and selecting cell B2 protects and then unprotects the sheet while displaying message boxes:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Row = 2 And Target.Column = 2 Then
strBook = ActiveWorkbook.Name
Me.Protect
Me.Unprotect
MsgBox "Worked from sheet", vbOKOnly, "Response"
Call TestMe(wksTest)
End If
End Sub
However if an ActiveX Command Button named "TestButton" is added to Sheet1 and this code is added:
Private Sub TestButton_Click()
strBook = ActiveWorkbook.Name
Me.Protect
Me.Unprotect
MsgBox "Worked from Button", vbOKOnly, "Response"
Call TestMe(wksTest)
End Sub
The workbook will no longer function if saved from 365 and opened with 2010 on a machine with only 2010 installed.
This is unique enough that it has been difficult to test. Currently, the only option I seem to have is replace all my command buttons with Form Controls. This also is a separate issue from the security update (which is really muddying the waters).
I would love to get feedback on possible fixes for this issue or even just confirmation from others that this is an Excel issue and not somehow limited to our installation.
Thanks
I was looking for help on a similar question and stumbled on this info on the Microsoft help site. If this doesn't solve the problem you have, it might be a step in the right direction:
"If a workbook contains ActiveX controls that are considered to be Unsafe for Initialization (UFI), they are lost when you save the workbook to an earlier Excel file format. You may want to mark those controls as Safe for Initialization (SFI).
What to do: If you open a workbook that contains uninitialized ActiveX controls, and the workbook is set to high security, you must first use the Message Bar to enable them before they can be initialized."

VBA Dialogs.Show doesn't display warning message

Have Excel (2010 in my case but I think it will be the same also in other versions) with two workbooks. Save first one with name "1.xlx" (example) via Save As dialog. Save second one with the same name "1.xlx" to different location. Excel will not allow it with following warning message:
"You cannot save this workbook with the same name as another open workbook or add-in. Choose a different name, or close the other workbook or add-in before saving."
So far so good. But my problem is that I need to invoke dialog via VBA. I am using following code:
Sub test()
Application.Dialogs(XlBuiltInDialog.xlDialogSaveAs).Show
End Sub
Now I am trying to save second workbook (with the same name to different location) but when I click to 'Save' button nothing happen, no warning message. If I wouldn't know what is wrong it would be very difficult to tell. I didn't change any setting (there is nothing as DisplayAlerts set to true or so). Any idea how make SaveAs dialog invoked via VBA to display similar warnings?
I'm not sure why that doesn't give you an error, but it doesn't me either. If you use Application.FileDialog, you can get that error.
Sub testts()
With Application.FileDialog(msoFileDialogSaveAs)
.Show
.Execute
End With
End Sub
Or you could use GetSaveAsFileName and check the names of all the open workbooks and generate the error yourself.
Can you try with the below code on starting on your code.
Application.DisplayAlerts = True

Cancel External Query in Excel VBA

I have created an Excel Spreadsheet which helps with data analysis from an Oracle database.
The user enters then clicks the "Refresh Query" button which generates a query for Oracle to execute. The query takes a minute or so to complete. Although the VBA code does not hang on ".Refresh", all Excel windows remain frozen until the query completes.
Sub refreshQuery_click()
Dim queryStr as String
' Validate parameters and generate query
' ** Code not included **
'
' Refresh Query
With ActiveWorkbook.Connections("Connection").OLEDBConnection
.CommandText = queryStr
.Refresh
End With
End Sub
Is there a way for the user to manually cancel the query (calling .CancelRefresh) while the Excel user-interface is frozen?
EDIT I don't know if the following is worth noting or regular behavior. While the query is executing, all open Excel windows (including the VBA Editor) become "Not Responding" in Task Manager. Neither pressing Esc nor Ctrl+Break will cancel the script. Also, calling DoEvents (either before or after .Refresh) does not change this behavior.
Here's a method that I know will work. However, there are some complications.
Here's how it's done:
Put the spreadsheet with the data in a separate workbook. This worksheet should execute the refresh query when it's opened and then close once the data is updated.
Create a batch file to call the "Data" Excel file.
Within a different workbook, create a procedure (macro) for the user to call. This procedure will call the batch file, which subsequently calls the Excel file. Since you are calling a batch file and not Excel directly, the Excel procedure will continue because the command shell is released so quickly and opens the other Excel file in a different thread. This allows you to continue working within the main Excel file.
Here are some complications:
I included a method to alert the user that the data has been udpated. There are timing issues where it's possible to try to check if the data has been update when the workbook is not accessible, which forces the user to try to update values. I included a method called my time which pauses the execution of the code so it only checks every so many seconds.
The updated worksheet will pop up in a new window, so the user will need to click on their original worksheet and keep working. You could learn to hide this if you're comfortable with Windows scripting (I haven't learned that yet).
Here are some files and code. Be sure to read the comments in the code for why some things are there.
FILE: C:\DataUpdate.xls
We'll make a workbook called "DataUpdate.xls" and put it in our C:\ folder. In cell A1 of Sheet1, we'll add our QueryTable which grabs external data.
Option Explicit
Sub UpdateTable()
Dim ws As Worksheet
Dim qt As QueryTable
Set ws = Worksheets("Sheet1")
Set qt = ws.Range("A1").QueryTable
qt.Refresh BackgroundQuery:=False
End Sub
Sub OnWorkbookOpen()
Dim wb As Workbook
Set wb = ActiveWorkbook
'I put this If statement in so I can change the file's
'name and then edit the file without code
'running. You may find a better way to do this.
If ActiveWorkbook.Name = "DataUpdate.xls" Then
UpdateTable
'I update a cell in a different sheet once the update is completed.
'I'll check this cell from the "user workbook" to see when the data's been updated.
Sheets("Sheet2").Range("A1").Value = "Update Table Completed " & Now()
wb.Save
Application.Quit
End If
End Sub
In the ThisWorkbook object in Excel, there's a procedure called Workbook_Open(). It should look like the following so it executes the update code when it is opened.
Private Sub Workbook_Open()
OnWorkbookOpen
End Sub
NOTE: I found a bug when this file closed if 1) you accessed the file from the command line or shell and 2) you have the Office Live Add-in installed. If you have the Office Live Add-in installed, it will throw an exception on exit.
FILE: C:\RunExcel.bat
Next, we're going to create a batch file that will open the Excel file we just made. The reason that call the Excel file from within the batch file and not directly from the other Excel file using Shell is because Shell will not continue until the other application closes (at least when using Excel.exe "c:\File.xls"). The batch file, however, runs its code and then immediately closes, thus allowing the original code that called it to continue. This is what will let your uses continue working in Excel.
All this file needs is:
cd "C:\Program Files\Microsoft Office\Office10\"
Excel.exe "C:\DataUpdate.xls"
If you're handy with Windows Scripting, you do fancy things like open the window in a hidden mode or pass a parameter of the file name or Excel location. I kept it simple with a batch file.
FILE: C:\UserWorkbook.xls
This is the file that the user will open to "do their work in." They'll call the code to update the other workbook from within this workbook and they'll still be able to work in this workbook while this one is updating.
You need a cell in this workbook where you'll check the "Update Table Completed" cell from the DataUpdate workbook. I chose cell G1 in Sheet1 for my example.
Add the following code to a VBA module in this workbook:
Option Explicit
Sub UpdateOtherWorkbook()
Dim strFilePath As String
Dim intOpenMode As Integer
Dim strCallPath As String
Dim strCellValue As String
Dim strCellFormula As String
Dim ws As Worksheet
Dim rng As Range
Set ws = Worksheets("Sheet1")
Set rng = ws.Range("G1")
strCellFormula = "='C:\[DataUpdate.xls]Sheet2'!A1"
'This makes sure the formula has the most recent "Updated" value
'from the data file.
rng.Formula = strCellFormula
strFilePath = "C:\RunExcel.bat"
intOpenMode = vbHide
'This will call the batch file that calls the Excel file.
'Since the batch file executes it's code and then closes,
'the Excel file will be able to keep running.
Shell strFilePath, intOpenMode
'This method, defined below, will alert the user with a
'message box once the update is complete. We know that
'the update is complete because the "Updated" value will
'have changed in the Data workbook.
AlertWhenChanged
End Sub
'
Sub AlertWhenChanged()
Dim strCellValue As String
Dim strUpdatedCellValue As String
Dim strCellFormula As String
Dim ws As Worksheet
Dim rng As Range
Set ws = Worksheets("Sheet1")
Set rng = ws.Range("G1")
strCellFormula = "='C:\[DataUpdate.xls]Sheet2'!A1"
strCellValue = rng.Value
strUpdatedCellValue = strCellValue
'This will check every 4 seconds to see if the Update value of the
'Data workbook has been changed. MyWait is included to make sure
'we don't try to access the Data file while it is inaccessible.
'During this entire process, the user is still able to work.
Do While strCellValue = strUpdatedCellValue
MyWait 2
rng.Formula = strCellFormula
MyWait 2
strUpdatedCellValue = rng.Value
DoEvents
Loop
MsgBox "Data Has Been Updated!"
End Sub
'
Sub MyWait(lngSeconds As Long)
Dim dtmNewTime As Date
dtmNewTime = DateAdd("s", lngSeconds, Now)
Do While Now < dtmNewTime
DoEvents
Loop
End Sub
As you can see, I constantly updated the formula in the "Listening Cell" to see when the other cell was updated. Once the data workbook has been updated, I'm not sure how you'd force an update in code without rewriting all the cells. Closing the workbook and reopening it should refresh the values, but I'm not sure of the best way to do it in code.
This whole process works because you're using a batch file to call Excel into a different thread from the original file. This allows you to work in the original file and still be alerted when the other file has been updated.
Good luck!
EDIT: Rather than include a more complete answer in this same answer, I've created a separate answer dedicated entirely to that solution. Check it out below (or above if it gets voted up)
Your users can break the VBA function by pressing Ctrl+Break on the keyboard. However, I've found that this can cause your functions to randomly break until each time any function is run. It goes away when the computer is restarted.
If you open this file in a new instance of Excel (meaning, go to Start > Programs and open Excel from there), I think that the only workbook that will be frozen will be the one executing the code. Other intances of Excel shouldn't be affected.
Lastly, you might research the DoEvents functions, which yields execution back to the Operating System so that it can process other events. I'm not sure if it would work in your case, but you could look into it. That way you can do other things while the process is being completed (It's kind of dangerous because the user can then change the state of your application while the process is working).
I believe I know a way that actually will work, but it's complicated and I don't have the code in front of me. It involves creating a separate instance of the Excel application in code and attaching a handler to the execution of that instance. You include the DoEvents part of the code in a loop that releases once the application closes. The other instantiated Excel application has the sole purpose of opening a file to execute a script and then close itself. I've done something like this before so I know that it works. I'll see if I can find the code tomorrow and add it.
Well, you could consider the old-fashion way -- split the query into smaller batches and use Do Events in between batches.
You could try XLLoop. This lets you write excel functions (UDfs) on an external server. It includes server implementations in many languages (eg. Java, Ruby, Python, PHP).
You could then connect to your oracle database (and potentially add a caching layer) and serve up the data to your spreadsheet that way.
The XLL also has a feature to popup a "busy" GUI that lets the user cancel the function call (which disconnects from the server).
BTW, I work on the project so let me know if you have any questions.