Geo Koro
Geo Koro

Reputation: 75

Excel VBA - Why am I getting Runtime Error

Everyone,

Can someone help me understand what is wrong with the following code?

Sub CombDelDuplShNamCellAdd()

Dim ProdVal As New Scripting.Dictionary
ProdVal.Add "ULP", 100000
ProdVal.Add "PULP", 200000
ProdVal.Add "SPULP", 300000
ProdVal.Add "XLSD", 400000
ProdVal.Add "ALPINE", 500000
ProdVal.Add "JET", 600000
ProdVal.Add "SLOPS", 700000


Dim AdmSh, CalSh As Worksheet, ProdLinLowRan, ProdLinUppRan As Range

Set CalSh = Sheets("Calendar")
Set AdmSh = Sheets("AdminSheet")

'''' Data Prep Table
ProdLinLowRan = Range(AdmSh.Range("B10")).Offset(1).Address
ProdLinUppRan = Range(AdmSh.Range("B10")).Offset(69).Address

MsgBox ProdLinLowRan

enter image description here enter image description here

Why am I getting this error? Can't understand. I'm newbie btw.

Cheers.

Upvotes: 1

Views: 282

Answers (2)

FunThomas
FunThomas

Reputation: 29171

There are multiple issues with your code.

a) Your variable declaration is flawed. You will need to specify the variable type for every variable separately. If you write

Dim AdmSh, CalSh As Worksheet, ProdLinLowRan, ProdLinUppRan As Range

The variables AdmSh and ProdLinLowRan will not be of type Worksheet resp. Range, they will be of type Variant. You need to use (split into 2 lines just for readability)

Dim AdmSh as Worksheet, CalSh As Worksheet
Dim ProdLinLowRan as Range, ProdLinUppRan As Range

b) AdmSh.Range("B10").Offset(69) is already a Range. No need to write Range around it.

c) If you want to assign an object (and a Range is an object), you need to specify Set.

Set ProdLinLowRan= AdmSh.Range("B10").Offset(1)
Set ProdLinUppRan = AdmSh.Range("B10").Offset(69)

What currently is going on in your code with the lines:

ProdLinLowRan = Range(AdmSh.Range("B10")).Offset(1).Address
ProdLinUppRan = Range(AdmSh.Range("B10")).Offset(69).Address

The right part (Range(AdmSh.Range("B10")).Offset(1).Address) will return the address of a range as String ($B$11). As ProdLinLowRan is declared as Variant, VBA will write that string into ProdLinLowRan and assume that you have a String variable. Not what you intended, but possible.

However, ProdLinUppRan is declared as Range, but not assigned (in VBA terms, it is Nothing). Writing something into a Range writes something into a cell, eg ProdLinUppRan = 3 would write the number 3 into that cell, but only if the range variable is pointing to something. As this is not the case, you will get the runtime error.

Upvotes: 1

Gustav
Gustav

Reputation: 55816

You have Dim'ed incorrectly.

Dim AdmSh As Worksheet
Dim CalSh As Worksheet
Dim ProdLinLowRan As Range
Dim ProdLinUppRan As Range

All these objects need a Set.

The reason for ProdLinLowRan not failing is, that you dim it as Variant, which is very forgiving.

Upvotes: 2

Related Questions