Home » excel » excel – Using variables created from ActiveWorkbook and ActiveSheet

excel – Using variables created from ActiveWorkbook and ActiveSheet

Posted by: admin May 14, 2020 Leave a comment

Questions:

I feel sheepish asking this – must be pretty simple – but I’ve spent hours combing through books, websites and various blocks of code trying to figure it out, and still can’t make it work. What am I missing?

I’m trying to assign ActiveWorkbook and ActiveSheet to variables so that they can be specified directly instead of implied. The macro handles three different workbooks. Two of them are static names so I can reference them by name, no problem. But the active file name will be different every time the macro is run.

The code works when the ActiveWorkbook and ActiveSheet are implied:

Dim callsWB As Workbook
Dim callsWS As Worksheet
Set callsWB = ActiveWorkbook
Set callsWS = ActiveSheet

Dim lastRow As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row

Dim pType As Range
Set pType = Range("N3" & ":N" & lastRow).Find("P", LookIn:=xlValues)

but not when I try to use the variables:

Dim callsWB As Workbook
Dim callsWS As Worksheet
Set callsWB = ActiveWorkbook
Set callsWS = ActiveSheet

Dim lastRow As Long
lastRow = callsWB.callsWS.Cells(Rows.Count, 1).End(xlUp).Row

Dim pType As Range
Set pType = callsWB.callsWS.Range("N3" & ":N" & lastRow).Find("P",LookIn:=xlValues)

I’ve also tried various syntax like

callsWB(callsWS).Range("N3")

and a number of different With statements. If anyone could point me in the right direction I’d be so grateful.

How to&Answers:

When you Set callsWS = ActiveSheet it sets the workbook as part of the variable also.

So callsWB.callsWS. is like ActiveWorkbook.ActiveWorkbook.ActiveSheet

Set the workbook when you set the worksheet:

Set callsWS = callsVB.worksheets("Sheet1")

But since you are calling the ActiveSheet the Active Workbook is implied so Set callsWS = ActiveSheet is sufficient

then just use the worksheet:

Dim callsWB As Workbook 
Dim callsWS As Worksheet
Set callsWB = ActiveWorkbook 
Set callsWS = ActiveSheet

Dim lastRow As Long
lastRow = callsWS.Cells(Rows.Count, 1).End(xlUp).Row

Dim pType As Range
Set pType = callsWS.Range("N3" & ":N" & lastRow).Find("P",LookIn:=xlValues)