# Countif Error

#### gaurav.inani

##### New Member
Hi,

I have created a new excel macro enabled workbook in Excel 2007.

I have entered the following in Sheet1
A1 = Name
A2 = Mike
A3 = Jullian
A4 = Peter
A5 = Rusell

and in Column B, as

B1 = Say
B2 = Hi
B3 = Hello
B4 = Hi
B5 = Hi

in my sheet2 i have
A1=Hi
A2=Hello

and then I have activated sheet2 and trying to enter formula through VBA

Sub test()
dim r as range
Sheet(ActiveSheet.Index - 1).Select
Set r = Columns("B:B")
Sheet(ActiveSheet.Index + 1).Select
Range("B1").Select
Activecell.Formula = "=Countif(r,A1)"
End sub

(This I am doing because the user does not know which sheet is activated and hence in Sheet2 the forumla have to return the value 3)

But it is generating error, can anyone help me on this topic.

### Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.

#### gaurav.inani

##### New Member
and when i am trying this formula this is working fine

activecell.formulaR1C1 = "=COUNTIF(Sheet1!B1:B5,Sheet2!A1)"

But what if I dont know from which sheet I have to select range then what I have to do.......

#### Norie

##### Well-known Member
It's pretty unclear what you want to do here.

What would you expect r to be replaced with when the formula was on the worksheet?

Why are you using ActiveSheet and Index for the worksheets?

#### gaurav.inani

##### New Member
What i am trying to do is
in Sheet2 it will reply 3 when i enter the formula of countif based on the range selected from Sheet1 i.e. B1:B5
But my main concern is what if the user rename the sheet Sheet1 to Hi then formula doesn't work.....
As i am new i dont know how to use code tags

#### Norie

##### Well-known Member

Well you can easily get a worksheet's name using it's Name property.

You could then incorporate that into the formula.
Rich (BB code):
``````Range("B1").Formula = "=Countif('" & Sheets(ActiveSheet.Index - 1).Name & "'!B:B,A1)"
``````

#### gaurav.inani

##### New Member
Hey thanks a lot Norie, its working now.......... But will u please explain me the logic of the same

"=Countif('" & Sheets(ActiveSheet.Index - 1).Name & "'!B:B,A1)"

As i am new to VBE i wanted to know the logic.....

specially

'
&

And one more thing :

I want to insert the nos. of rows in Sheet3 based on the value in Cell B1 in Sheet2
But again I dont know the name of Sheet3 so do i use the same format or the different one???

Last edited:

#### Norie

##### Well-known Member
Well the ' is nothing to do with VBA, it's needed for the formula on the worksheet to deal with things like spaces.

#### gaurav.inani

##### New Member
And one more thing :

I want to insert the nos. of rows in Sheet3 based on the value in Cell B1 in Sheet2
But again I dont know the name of Sheet3 so do i use the same format or the different one???

Here in this case 3.

1,106,997
Messages
5,514,698
Members
409,014
Latest member
evenyougreg