I have been developing a VBA, UserForm1 program for the past few weeks and I have performed numerous test and never once had this problem.
The code, shown below, is part of the Initialization routine. I made some enhancements to the program, far deeper in the code than the code under discussion. Now, I can't get past this point in the program. I replaced "Activate" with "Select", but this did not affect the outcome, i.e., an aborted run.
Please, can someone suggest what I am doing wrong? Or, how can a program that been tested dozens of times, suddenly develop a fault out of thin air?
'======================================================================
Dim WPA() As Variant 'Workbook path for Category Class
Dim WBA() As Variant 'Workbook name for Category Class
Dim WSA() As Variant 'Worksheet name for Category Class
'======================================================================
Dim WBK() As Workbook
..........
Set WBK(S) = Workbooks.Open(WPA(S))
Workbooks(WBA(S)).Worksheets(WSA(S)).Activate 'Activate Worksheet
NWS(S) = CheckSheetExists(WSA(S)) 'Check for Worksheet
..........
Function CheckSheetExists(SheetName) As Boolean
CheckSheetExists = Evaluate("ISREF('" & SheetName & "'!A1)")
If CheckSheetExists = False Then
MsgBox "Worksheet " & SheetName & " does not exist. Run aborted."
End '<==================Run aborts
End If
End Function
It looks like you are using global variables?
If so, you should be aware that they are not as permanent as you might expect.
There are a number of things which cause global variables to reset and become undefined.
See this answer for more info: https://stackoverflow.com/a/7043901/1473412
Using "End"
An unhandled runtime error
Editing code
Closing the workbook containing the VB project
Is it possible that the "enhancements to the program, far deeper in the code than the code under discussion", causes one of these things to happen, and so resets the global variables?
If you have to use global variables, you could store them safely in a worksheet. Or, everytime you try and use one, you could check that it is defined, and if not, redefine it?
That is a good question, Storaxs' answer should have fixed this though to my knowledge.
However when something like this happens I try to create a whole new workbook and paste all of this code into it (just for the sheet in question) and then copy all the cells data into the new sheets.
This has saved me once before and it may help you in this case as well.
I also recommend not deleting your old workbook in case you don't port everything over.
If this still doesn't work let us know and we will continue to look into this.
Related
I am attempting to copy different images to different worksheets of my Workbook using the following code below. I am changing the Target Worksheet Dynamically in a different sub, with a String Variable in the Global Declarations section. I can see the variable being passed to the sub and in fact it works the first pass through the code, but when I attempt to change the "TargetSheetIni" variable to a new sheet, it continues to use the first original sheet as it loops through.
Can you not change a target sheet after using the Set keyword? Should I refer to the sheet directly instead?
Sub Test1()
Dim TargetWS, SourceWS As Worksheet
Set TargetWS = Worksheets(TargetSheetIni)
Set SourceWS = Worksheets("Images")
DoEvents
SourceWS.Shapes(CurrentImageId).Copy
DoEvents
TargetWS.Paste Range(ColumnLetter2 & RwCnter)
DoEvents
End Sub
I think I may have figured it out. As far as I can tell the issue may be that I used the Copy Sheet Functionality in Excel when I originally created the target sheets. And even though I renamed the sheets both on the tab below and in the project editor... for some reason VBA kept targeting only the original sheet
I proved this by changing my code around to explicitly call the sheet I wanted to target like so:
ActiveWorkbook.Worksheets("Sheet2").Paste Range("I2")
And even doing that it would target sheet 1 for the paste command instead of the expected sheet 2. I deleted the three copy sheets and created a new one from scratch and re-executed code and now it targets sheet 2 as expected.
I found this article that sort of explains it I guess...
https://www.spreadsheetsmadeeasy.com/7-common-vba-mistakes-to-avoid/
Ok my last answer may have not been correct. It appears as though for some reason inserting an ws.activate caused my code to start workin.g
Very frustrating fix. as I have always heard to avoid using that.
Earlier this morning I asked my first question. Whilst investigating the suggestion put forward by Marco, I encountered a "does not make sense" situation. I went back to the immediately previous version of the macro suite to see what behaviour that gave. Let's call these Suite A and Suite B
In both Suite A and B there is the following code:
Public wsTemp As Worksheet
Sub DrillDown()
In Suite A there is the following:
Sub HandleNewFileNumber()
If iK <> 0 Then
wbTgt.Close
End If
Set wsTemp = ThisWorkbook.Sheets.Add(After:=Worksheets(1))
In Suite B there is:
Sub HandleNewFileNumber()
If iK <> 0 Then
wbTgt.Close
End If
Set wsTemp = ThisWorkbook.Sheets.Add(After:=Worksheets(1))
No, I have not simply copied the same code twice. I took each piece of code out of the two separate workbooks. The code is identical.
When I run the macro suite A everything runs through to successful completion. When I run macro suite B I get Error 1004. In both cases the Set of wsTemp is the first time wsTemp has been referenced.
I am at a loss to understand how the same code can give two radically different results.
Try
Set wsTemp = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Worksheets(1))
Or
With ThisWorkbook
Set wsTemp = .Sheets.Add(After:=.Worksheets(1))
End With
It's a very common problem: When you access an object from Excel (Sheet, Range, ...) and don't specify where it belongs to (eg a Worksheet belongs to a Workbook, a Range belongs to a Worksheet), VBA assumes you are referring to whatever is currently active (currently having the input focus).
If you write Worksheets(1), Excel will translate this to the first worksheet of the current active Workbook. When ThisWorkbook is not the active workbook, this will lead to the situation that you ask Excel to add a sheet to one workbook but put it after the sheet of another workbook - and that's not possible and will throw an error.
VBA beginners will often try to solve this by put activate-statements in the code, but that's the wrong attempt. There is no need to activate anything. Instead, just tell VBA exactly what you want. By writing ThisWorkbook.Worksheets(1), you specify that you mean the first sheet of ThisWorkbook (which is the WB where the code lives in). The second piece of code (using With) is just another way of writing it - but note that .Worksheet has a leading . that signals that we are accessing the sheet of the Workbook specified in the With-clause.
As a rule of thumb, never put anything in your code that let's VBA guess something.
Having spent an hour or two working through the entire suite of macros, applying the technique suggested by #Fun Thomas, and tidying up some other loose code as I went along, I can no longer reproduce the failure on my most up-to-date version of the macros.
Thank you everybody for your thoughts and suggestions. I will now concentrate on offering further diagnostic data to my very original post about flickering grey screens when opening workbooks.
I have a userform that is supposed to insert a row on Sheet3 and populate some cells in that row with some values. it works great as long as I have sheet3 displayed. (The form is shown modeless to give me access to the sheets).
Anyway, I happened to have another sheet active and ran it again and was surprised to see it inserted the row not in sheet3, but in the one I had displayed... (Thank God I saved first!)
In the code, I specified a range object as follows to find the insertion point: (I'll truncate the code a bit to keep it simple)
Dim RecordRange As Range
Set RecordRange = Sheet3.Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1,0).EntireRow.Insert
blah blah blah.
A workaround is to activate the sheet first:
Sheet3.Activate
That at least inserts into the correct sheet, but I'd rather not have sheet3 be displayed when I add the record, so I even surrounded that line with:
Application.ScreenUpdating = False
Sheet3.Activate
Application.ScreenUpdating = True
unfortunately, ScreenUpdating doesn't work from within a Userform Code module, so that bites...
I still don't understand why it chooses to insert the row into whatever sheet is active, when I've already specified sheet3 in the code. I have another Macro very similar that doesn't have this problem.
any ideas?
...so you figure your workaround needs a workaround? Hmm... I think that qualifies as a double-negative since a workaround is supposed to, by definition, fix problems rather than cause them...
A workaround is a bypass of a recognized problem in a system. A
workaround is typically a temporary fix that implies that a genuine
solution to the problem is needed. But workarounds are frequently as
creative as true solutions, involving outside the box thinking in
their creation.
Typically they are considered brittle in that they will not respond
well to further pressure from a system beyond the original design. In
implementing a workaround it is important to flag the change so as to
later implement a proper solution.
Placing pressure on a workaround may result in later system failures.
For example, in computer programming workarounds are often used to
address a problem or anti-pattern in a library, such as an incorrect
return value. When the library is changed, the workaround may break
the overall program functionality, effectively becoming an
anti-pattern, since it may expect the older, wrong behaviour from the
library. (Wikipedia)
Just sayin'... :-)
So instead of fixing the workaround, your original issue is (thankfully) straightforward.
You're using Sheet3 as an object, and I suspect you haven't assigned anything (like Worksheets("Sheet3") to an object called Sheet3.
Try this instead:
Dim RecordRange As Range
Set RecordRange = Worksheets("Sheet3").Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1,0).EntireRow.Insert
If you indeed intended to use Sheet3 as an object then make sure it's declared as set, so for example you could instead use:
Dim RecordRange As Range
Dim Sheet3 As Worksheet
Set Sheet3 = Worksheets("Sheet3")
Set RecordRange = Sheet3.Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1, 0).EntireRow.Insert
Also, just to point out: If either of these solves your issue then the problem would've "made itself known", by including one line at the top of every module (at least during development & troubleshooting):
Option Explicit
This link has a short explanation, but basically it forces you to properly declare all variables (thus helping to prevent future workarounds!)
First: I'm using Excel 2007, but the code has to work for Excel 2003 as well.
My problem is the following: I need to access cells in a different workbook, which may be closed. The following code can be found all around the web:
Function Foo()
Dim cell As Range
Dim wbk As Workbook
Set wbk = Workbooks.Open("correct absolute path")
' wbk is Nothing here so the next statement fails.
Set cell = wbk.Worksheets("Sheet1").Range("A1")
Foo = cell.Value
wbk.Close
End Function
sadly, wbk is Nothing after the open statement (I'd love to give a better error message, but no idea how I'd do that; what I'd give for a real IDE and an useful language :/). The absolute path is correct and points to a valid excel xlsx file.
Also I assume the best way to do this, is to "cache" the workbook and not open/close it every time the function is called? Any possible problems with that (apart from having to handle the situation when the workbook is already open obviously)?
Image while stepping through:
I can reproduce this problem. It only happens to me when I attempt to paste this code into a user-defined function.
I believe this is by design (the quote is for XL 2003, but the same thing happens to me on XL 2010)
Using VBA keywords in custom functions
The number of VBA keywords you can use in custom functions is smaller than the number you can use in macros. Custom functions are not allowed to do anything other than return a value to a formula in a worksheet or to an expression used in another VBA macro or function. For example, custom functions cannot resize windows, edit a formula in a cell, or change the font, color, or pattern options for the text in a cell. If you include "action" code of this kind in a function procedure, the function returns the #VALUE! error.
http://office.microsoft.com/en-us/excel-help/creating-custom-functions-HA001111701.aspx
The only workaround I've found is to call this kind of code via a normal macro. Something like selecting the cells to apply it to, then looping over Selection or the like.
You can use this (similar to what Bruno Leite proposed, but much simpler to write):
Dim excelApp As New Excel.Application
excelApp.Visible = False
Set WB = excelApp.Workbooks.Open(FileName, xlUpdateLinksNever, True)
As UDFs are called repeatedly, you should make sure to do an excelApp.Quit before exiting the function (and a WB.close(False) before) to avoid having countless Excel instances running on your box.
I spent some thoughts on it and came to the conclusion that you cannot mess around with the workbooks of the current instance of excel while executing a UDF. On the other hand, opening a second instance of excel will do the job without interference.
To get data from Workbook without is open, you can use this, with ADO connection.
To use in Excel 2007 change this
Microsoft.Jet.OLEDB.4.0
to
Provider=Microsoft.ACE.OLEDB.12.0
and
Extended Properties=\"Excel 8.0;HDR=Yes;\
to
Extended Properties=\"Excel 12.0;HDR=Yes;\
[]'s
The workaround of putting my routine into a separate macro in the workbook module, and calling that macro from the Workbook_BeforeSave code, seems to have done the trick.
I've had a similar issue, but in my case it's a "Workbooks.Open(filename)" command at the start of a small routine embedded in Workbook_BeforeSave. VBA just skips right over the line of code as if it weren't there, it doesn't even report an Err.Code or Err.Description.
The only clue for me was that it's part of the Workbook_BeforeSave routine, and the limits with Functions above seem to indicate that could be a possible cause. So I dug around further to find more details.
It seems that Workbook_BeforeSave disables Excel from opening more files, and I guess there's a good reason for doing that, since the File > Open option is still visible in the File menu, but it can't be clicked. Strangely, the Open toolbar icon/button still works, and so whilst I can manually open the file from there, I wonder if it's because it's impossible to call this action from VBA code and that's why they allowed it?
You don't have to "Set" a cell, It's part of the workbook class (as far as I know). Just use the following...
foo = wbk.Worksheets("Sheet1").Range("A1").Value
I would suggest that you open you the new workbook upon opening the calling workbook, in the worbook_open event.
You then store the new workbook reference in a global variable.
Then the function called by your cell uses the said global variable instead of trying to open a new workbook. This way you go around the limitations.
PS : Of course global variable are to be avoided, some sort of container would be better than a direct global variable.
You can check the error in a proper way by using the following code:
filelocation = c:\whatever\file.xlsx
On Error GoTo Handler 'this is key as if the next row returns an error while opening the file it will jump to the Handler down there.
Set wkb2 = Workbooks.Open(filelocation, ReadOnly)
Handler:
MsgBox "File " & filelocation & " does not exist or cannot be reached, please review and try again"
I know that this does not answer the question (that's why I also landed in this thread, as I cannot open the file and can't understand why is that so)
Cheers,
RV
My code is:
Sub zaa()
'code to find another open file that has the defined name "data"
' - useful where the name changes each month or week
For Each wb In Workbooks
On Error GoTo abcd
x = wb.Name
Workbooks(x).Activate
If Range("Data").Address <> "" Then y = wb.Name
Exit Sub
abcd:
Next wb
End Sub
Basic goal to find an Excel file with a specific named range when I know it exists but don't know the file name as it changes each week or month. Aim is to find the file and exit the sub at that point (or then do other code on that file and exit rather than going to other files.)
I find it works okay if I only have two files open but not if have more (unless the target one is second in line). Whilst I can run with what I have I thought others may benefit from what I have and I can have a more robust solution.
UPDATE:
Thanks to all those who have responded & to Mitch for putting original post in readable format! (I have since learnt how to correct that issue and to be able to copy code directly - which I have indicated in some comments below that I was having trouble with.)
I have had varying degrees of success - code from PaulStock & Reafidy both worked for me originally but PaulStock code has stopped working for me. Responses & code from Jean-François Corbett and Chris Neilsen have been helpful to me but presently when I run the code (as is) it appears to do nothing - ie doesn't leave the sheet I run it from (and that's not where the range name data appears). I was originally running the code in Excel 2007 in a sheet with other macros but to try and get different results have moved them to a stand alone sheet with no other macro files open. Have also tried running them from a file saved as '97-'03 format. Neither yielded different results. Others with more experience than I (see the errors I made evidenced in comments discussion with Reafidy & bear in mind that my original posted code was result of material found through google and modified by me for specific task & application and implication that I am not savvy enough to have come up with it on my own) may find other solutions better for them but for now:
I am more than happy as Reafidy's code works for me.
As I am not registered (I did try but it didn't work) and don't have enough reputation points I can not vote but I have put a check mark next to Reafidy's solution.
FURTHER UPDATE:
I have now discovered that PaulStock & Jean-François Corbett's code wasn't working for me due to a very minor discrepancy on my part - the code contained "Data" whilst my named range was "data". Making this change (to allow for case sensitivity) in their code means that both of their solutions now work for me and hence I have attempted to add a tick to their solutions! Unfortunately I have found that only one solution can have a tick.
I have also learnt that I took Chris' code too literally. In an effort to test each code 'as is' that is what I did. A simple additon of 'wb.activate' in the section where he has 'do stuff' makes the code do what I want.
THANKS again for all four contributions.
You're doing a few convoluted things in your code, and I think that's what's confusing the issue.
Having you error handler (abcd:) start in the middle of a For...Next loop is incredibly bad practice and can only lead to confusion. I can't think of a reason why this should ever be done.
Anyhow, there's no need to use error handling for this task. I understand that there are exceptional cases where bad VBA design forces us to use error handling instead of what should be built-in VBA functionality (e.g. testing whether a non-Variant array has been allocated), but this is not one of those cases. There's a standard way to do it (.Names collection of workbook object), and using error handling instead of this is messy and convoluted and asking for trouble.
Also, why say
x = wb.Name
Workbooks(x).Activate
when you can just say wb.Activate? You're not using x for anything. Or y, for that matter.
The following works and is both simplified and optimised, relative to your original code as well as to the other answers that have been given up to now:
Sub zaa2()
Dim wb As Workbook
Dim nm As Name
For Each wb In Workbooks
For Each nm In wb.Names
If nm.Name = "Data" Then
wb.Activate
Exit Sub
End If
Next
Next wb
End Sub
' A workbook containing a range named "Data" is now activated
' (if one is found amongst the open workbooks).
' Note that there may be more than one, but only the first found is activated...
EDIT: In your comment, you mention you had trouble due to confusion between uppercase "Data" and lowercase "data". To guard against this in the future, one possibility is to ignore case. This could be done as follows:
If StrComp(nm.Name, "data", vbTextCompare) = 0 Then
or
If LCase(nm.Name) = "data" Then
Both will return True if nm.Name is "Data", "data", "dATa", etc.
You can't use error handling like that. Either move the error handling out of the loop or reset the error handler each time it occurs, so use error handling like this:
A much preferred alternative would be:
Sub Test()
For Each wb In Workbooks
x = wb.Name
Workbooks(x).Activate
If RangeExists("Data") Then
y = wb.Name
Exit Sub
End If
Next wb
End Sub
Function RangeExists(s As String) As Boolean
On Error Resume Next
RangeExists = Range(s).Count > 0
End Function
EDIT:
#Jean-François Corbett, I have to say you a very quick to jump on the down vote button. The first solution I posted was because I made the assumption that the OP was not posting his entire code hence why I did not attempt to simplify it or "clean it up" like I usually do. I agree I did not word my answer well, but with regard to the first solution I was trying to demonstrate that he needed to reset the error handler. Unfortunately I should have said a "prefered alternative would be".
#Derek, Sorry I was unable to answer your further questions in time. Obviously you are free to choose whatever method you like. In my opinion the multiple loop solution provided by others which digs into the workbook name collection is unnecessary and long winded. Now more importantly the name collection can contain names which refer to a constant, formula, or a range. I presume you want to only check if the defined name is specifically a named range which means the looping method provided by others would need to be adjusted to be reliable.
I agree with comments made by others that error handling should be avoided BUT unnecessary looping in excel can be as much of an evil as using error handling and personally I avoid it like the plague.
The function above can be placed in its own module and be reused as much as you like. It is quick, reliable, avoids unnecessary looping, checks SPECIFICALLY for a named range in a workbook and is the most widely accepted/used method for checking if a named range exists within the excel vba community (by this I mean using a function and error handling over looping through the name collection). Do a google search for "Check If Named Range Exists" if you don't believe me. Or ask at www.ozgrid.com/forum if you want other excel vba experts opinion's.
Now that I know you have posted your entire code and that you did not intend to activate every workbook, you could use this code which will activate the first workbook found with the named range "data":
Sub Test3()
Dim wbLoop As Workbook
For Each wbLoop In Workbooks
If RangeExists("data", wbLoop) Then
wbLoop.Activate
Exit Sub
End If
Next wbLoop
End Sub
Function RangeExists(s As String, wb As Workbook) As Boolean
On Error Resume Next
RangeExists = wb.Names(s).RefersToRange.Count > 0
End Function
I completely understand the need for positive Criticism and I believe in the down vote system if it is used correctly. However, with two down votes for what I believe was a reasonable solution and along with my help with the ops formatting issues - unfortunately I cant help but feel like I want to distance myself from this forum.
Heres an alternative method without getting fancy with the error handler
Sub zaa()
Dim wb As Workbook
Dim CheckForNamedRange As Boolean
Dim nm As Name
On Error GoTo EH
For Each wb In Workbooks
CheckForNamedRange = True
Set nm = wb.Names("data")
If CheckForNamedRange Then
' Name found
' do stuff
Exit For
End If
Next
Exit Sub
EH:
If CheckForNamedRange Then
' Name not found
Err.Clear
CheckForNamedRange = False
Resume Next
Else
' Some other error occured, so handle it
'...
End If
End Sub
Try this code. Shouldn't have to worry about getting errors.
Sub zaa()
For Each wb In Workbooks
x = wb.Name
Workbooks(x).Activate
For Each n In Workbooks(x).Names
If n.Name = "Data" Then
y = wb.Name
Exit Sub
End If
Next
Next wb
End Sub