Excel VBA Script error Subscript out of range (Error 9) - excel

I'm not a specialist in VBA, but I have written a vba script for Excel, containg 12 modules with code, a lot of code. It's a very complex script but it's working fine. The problem is that it works only on my PCs. I tested it on 3 different PCs, with different Excel versions 2007, 2013 and 2016, and it works without any problem. But when I give the script to my colegues it gives errors.
Example:
This works for me:
Private Sub Test()
Workbooks("script").Sheets("Sheet1").Range("A:Z").ClearContents
......
It gives error Subscript out of range (Error 9) on other computers, I don't know why. If I change the code to:
Private Sub Test()
Set wb1 = ActiveWorkbook
wb1.Sheets("Sheet1").Range("A:Z").ClearContents
......
it works on other pcs too, but if I have to change the code this way, it will take a lot of time and most importantly, I can't test it if it works after the ammendments because it works for me anyway.
I found this thread VBA Subscript out of range - error 9 but I doesn't explain why It works for me on different Excel versions and it doesn't for other people.
Any help and suggestions will be appreciated.

It turned out that adding the file extension solves the problem as Tim suggested -
Workbooks("script.xlsx")
This way it works perfetcly on all PCs. It was something very simple, but I didn't know that.
Thanks again.

Related

Runtime Error subscript out of range when using a timed macro but with multiple sheets open at once

I am running a timed macro every half hour using this code:
Private Sub Workbook_Open()
MsgBox ("test")
Application.OnTime TimeValue("07:30:00"), "'Test.xlsm'!Daily.Daily"
End sub
This runs fine when I manually call the macro with a button, or I have the sheet active but I sit with multiple sheets open at once, when I am clicked into another sheet the runtime error 9 appears, subscript out of range - I understand this error, but dont know how I can either run it in the background or bring the sheet into the forefront so it isnt out of range
I have tried various online forum suggestions but they seem to be advising how to solve the runtime error due to a different cause than I am facing, im sure its a simple fix but I cant seem to ask google the right question - any suggestions would be great. thank you

getting Run-time Error 9: Subscript out of Range when trying to get value from a range in another open workbook

Whilst working in one workbook, I have code that puts the value of a named range in another open workbook (Workbooks("Draft Sales")) into a variable. I don't activate Workbooks("Draft Sales"). This works on my computer and one of my colleagues computers, but not on two other colleagues computers - where it brings up the error message "Run-time Error 9: Subscript out of Range".
I don't understand what the difference is. We're all on the same version of Excel (Excel 2013, 32 bit), and other parts of the code work fine on all four computers.
Here are two examples of code that works for two of us but not the other two:
varFormula = Workbooks("Draft Sales").Worksheets("HoldingBay").Range("InvOrCreditGrossTotalFormula").Formula
dblChkCalcd = Workbooks("Draft Sales").Worksheets("HoldingBay").Range("CheckCalculationIsFinished").Value
I've confirmed on my colleagues' computers that the "Draft Sales" workbook is open in the same instance of Excel, by running code to list all the open workbooks, and this does pick up the "Draft Sales" workbook.
Can anyone suggest why the code isn't working on my colleagues' computers?
Need to include the workbook extension:
Workbooks("Draft Sales.xlsx")

Excel 2016 VBA - Problems upgrading from Excel 2013

I developed several userforms and macros for a project in Excel 2013, but when I try to test them in Excel 2016, I get multiple errors on basic VBA functions.
For example I get an "Object doesn't support this property or method" error from the following code:
Private Sub ShowImpact()
FormImpact.Show
End Sub
Another example, the following code gives me an error "Can't find project or library" on the [RIMS_tbl] table reference. This is a named table in the document:
With FormImpact.cboIndustry
.ColumnCount = 11
.ColumnWidths = "0;50;0;0;0;0;0;0;0;0;0"
.RowSource = "=RIMS!" & [RIMS_tbl].Address
.BoundColumn = 1
.TextColumn = 2
End With
As another example, I get the same error message on "Format" method in the following code:
Private Sub txtConLand_AfterUpdate()
txtConLand = Format(txtConLand.Value, "#,##0")
End Sub
Lastly, I have a label that I'm using as a background on the form, which works fine in Excel 2013, but for some reason it covers all of the other controls in 2016, and I can't send it to the back.
I'm really hoping that there is some setting in 2016 that will fix all of these problems, because I can't figure out why so many things would break between these two versions. Thanks for your help!
As mentioned in the comments above, the solution to this problem was in eliminating missing references between different version numbers. In the Visual Basic interface, go to Tools->References. Check for missing references in all versions supported. Thanks #TimWilliams and #Stefan for the solution to this problem.
I never did figure out how to fix the problem of the z-order for the background label. Even setting the v-order for that label programmatically didn't work. But I did come up with a workaround. First I made a small white bitmap file. Then under the page settings, I set the background picture to be the bitmap file. Then I set set the "PictureSizeMode" property "fmPictureSizeModeStretch," which stretched the bitmap to fit the entire page. Finally, I added a border around the entire form.
I had the same problem when migrating an VBA powered Excel from Excel 2010 to 2016. Deselecting the ATLEntityPicker 1.0 Type Library from the References list solved it.

run time error 438 at ListObjects.Add method only on older version of Excel

It has been around 2 weeks since I started working on excel vba. I have a sub which converts a range of data into a table:
Sub RangeToTable(fileName, sheetname, rng, tblNm)
With Sheets(sheetname)
.ListObjects.Add(xlSrcRange, .Range(rng), , xlYes).Name = tblNm
.ListObjects(tblNm).ShowHeaders = False
.ListObjects(tblNm).TableStyle = "TableStyleLight15"
End With
End Sub
This sub works fine on my development machine (Win 7, Office 2007). But on our lab computer which is running Win XP and office 2000, I am getting a run time error 438 object does not support this property or method at Add method.
I have searched around for a solution and on MS website one of the causes of this problem is given as version mismatch, which is true in my case.
Can you guys please let me know a good solution for my problem?
Are there any work arounds?
Does this mean that any macro which deals with tables (ListObjects), I won't be able to run on an excel version which does not support tables?
Your help is appreciated,
Thanks,
DD.
Unfortunately this is not going to work. ListObjects as they are today were implemented in Excel 2010 and exist from 2003 onwards.
For Excel 2010 and 2013 see:
https://msdn.microsoft.com/en-us/library/office/ff195678(v=office.14).aspx
For 2007 see:
https://msdn.microsoft.com/en-us/library/bb223938(v=office.12).aspx
For 2003 see:
https://msdn.microsoft.com/en-us/library/office/aa174247(v=office.11).aspx
For 2000 and older: Doesn't exist so you need to code manually.
Chip Pearson confirms this here:
http://www.excelforum.com/excel-general/485029-listobject-in-excel-2000-a.html

#NAME? error in Excel for VBA Function

I am making my first VBA program and trying to run the following function. The function checks a specific named range for the first row which does not have a value greater than it's leading value, but less than 1.
Public Function findPurchase()
Dim CRT As Range
Set CRT = Range("CostRateTable")
Dim existsBetter As Boolean
existsBetter = True
Dim r As Integer
r = 2
Dim c As Integer
c = 4
While existsBetter
Dim Found As Boolean
FoundBetter = False
While Not FoundBetter And c <= CRT.Columns.Count
If CRT(r, c) > CRT(r, 2) And CRT(r, c) < 1 Then
FoundBetter = True
Else
c = c + 1
End If
Wend
existsBetter = FoundBetter
If existsBetter Then
r = r + 1
End If
Wend
findPurchase = CRT(r, 3)
'MsgBox(findPurchase)
End Function
I know the function does what it is supposed to because I have both manually checked the table of values, removed the comment ' from the MsgBox, and used the debug tools to step in and out of each of the functions steps as it went through the table. However, when I reference the function in Excel with =findPurchase() I'm given a #NAME? error. The function even shows up in the function auto-complete box when I begin to type its name. When I write other functions, both with and without parameters, I can reference them just fine, for example:
Function addtwo()
addtwo = 1 + 2
End Function
What am I doing wrong with my function which causes it not to work?
You are getting that error because you have a module with the same name as the function.
Change that name to say find_Purchase and everything will be fine :) See the image below...
I had the same issue myself. It turned out that I "Saved As..." another file and macros were not enabled for that file. No banner on the top appeared, but a #NAME? error was generated.
I reopened the file, enabled macros, and the problem was resolved.
Make sure you have placed the function in a Standard Module. The error message means Excel can't find the function.
When Excel opens an unkown workbook containing VBA-Code, it usually asks for macros to be enabled by the user (depending on the application settings).
If the user then enables the macros, all event-driven procedures will be started, such as auto_open or others.
Custom VBA Functions however require for a full recalculation of the workbook. Otherwise the functions return-value still is #NAME, as the calculation is only done directly after opening the workbook.
In order to work directly at the first time opening, one has to add the following line to the workbook_open event
'
' Workbook open event
Private Sub Workbook_Open()
Application.CalculateFullRebuild
End Sub
Check "Trust access to the VBA project object model" in Macro settings from Macros security
One reason for this problem is security restrictions.. I had this problem and I activate "Enable all macros" from security center, and the problem solved
I had a similar persistent problem with one of my functions when everything else seemed fine.
Open the worksheet & go to the Developer Tab. Open VBA, and back on the Developer ribbon select "View Code". See if it opens any similar Code (apart from your Module) specific to that worksheet (eg. Sheet2 (Code). I found that I had duplicated the code on the worksheet in addition to the Module. Delete the "worksheet" code. (You may need to save the workbook & re-open at this stage). When I deleted the worksheet code, the module function then worked.
In addition to checking some of the above mentioned items, you might need to specify the filename where the custom function is actually defined, e.g. cell content
=XLstart.xlsm!myCustomFunc(Arg1,Arg2)
where myCustomFunc is defined in the startup file XLstart.xlsm.
Following the Excel help for "Correct a #NAME? error":
In the formula bar, select the [suspect] function name.
In the Name Box (to the left of the formula bar), click the arrow and then select a [user-defined] function from the list that Excel suggests.
This will add the filename per the above format.
MS 2010, Windows 10.
Here's why I got that error. This answer is not provided so far.
If you have two or more workbooks (spreadsheets) open, then you may have your module under the other workbook - not the only you want to do the calculation on. This may seem impossible but ... as soon as you open the Developer/VBA code editor Excel wants to show you the structure (objects, modules, etc) of every open workbook. It's not what I expect as a developer, but there it is. So like me, you may have pressed 'Add module' and dropped the code in another workbook and worksheet.
If this is your issue, nothing mention above will work. Move your VBA module and code to the correct spreadsheet visible through this VBA code editor.
True,
I had the same (in Excel 2010) and when I migrated to Excel 2016 , the function prototype was shown, but when I completed the function, the #NAME error was shown with a pop-up... so the code was never triggered.
It turned out I had a Macro of the same name as a Sub or UDF function !
I renamed the Macro, and then it worked
Cheers
Another cause I found for the #NAME? error is that the macro workbook with the custom function has a range name the same as the function name. I changed the function name and solved the problem.
This solution applies to users with an Excel installed in another language than "United States English":
I had a similar problem when making a copy of the active workbook to duplicate it and immediately opened the copy afterwards:
Non-working code:
ThisWorkbook.SaveCopyAs NewFileName
Set wb = Workbooks.Open(FileName:=NewFileName)
This always showed me several cells with Error 2029 / "#NAME?". If I opened the Workbook "the official way" via the File-Menu it worked as expected.
I solved the issue by adding the parameter "local:=true" to the open statement:
Working code:
ThisWorkbook.SaveCopyAs NewFileName
Set wb = Workbooks.Open(FileName:=NewFileName, Local:=True)
as VBA expected english function names in my German workbook. With this parameter VBA is told directly to use the local names.
I hope that helps someone not to loose several hours, as I did...
Short answer - if the function was working before, RESTART YOUR COMPUTER.
Long answer - I had this same thing happen to me. The problem is that the function I had created had been working for months. Then one day it just started showing a #NAME error instead of working like it was before. I had tried closing all other excel workbooks and even closing excel all-together and re-opening the sheet. Nothing seemed to work. Then for kicks, I edited the code to where I knew VBA would complain that there is a compile error. Surprisingly, it didn't complain. OK... I saved and closed excel anyways and then restarted my computer.
Once rebooted, I re-opened the excel workbook. Then VBA finally gave me a compile error. So I changed my function back to the original code I had before and now the sheet is running the function like it is supposed to. No more #NAME error.
Not sure all of those steps are necessary, but simply restarting the computer seems to have fixed my issue.

Resources