VBA Issue


Posted by Sean on June 22, 2001 6:01 AM

I have the follow script in vba:

Sub ConditionalHide()
Dim cRange As String
cRange = Sheets(1).Range("A1")
For i = 2 To Sheets.Count
Sheets(i).Activate
If Range("A1").Value <> cRange Then
Sheets(i).Visible = False
Else: Sheets(i).Visible = True
End If
Next i
End Sub

The problem is that when it gets done searching through the sheets I end up on the last sheet it found instead of where I started. Is there an easy way to change this? I want to stay on the original sheet.

Posted by Dax on June 22, 2001 6:13 AM

Hello,

You just need to change a couple of lines. There's no need to activate each sheet as you can refer to it without activating it (plus the code will run quicker).

Sub ConditionalHide()
Dim cRange As String
cRange = Sheets(1).Range("A1")
For i = 2 To Sheets.Count
If Sheets(i).Range("A1").Value <> cRange Then
Sheets(i).Visible = False
Else: Sheets(i).Visible = True
End If
Next i
End Sub

HTH,
Dax.

Posted by Tuc on June 22, 2001 6:17 AM

Sure. The easiest way is to capture the worksheet (and Cell) that you are starting at.

In your code, before you do anything else declare a worksheet object and capture where you are at. Something like:

Dim wsCurrent as worksheet
set wsCurrent = activesheet

Then when you are done processing you check to see if you have changed location during the processing, either intentionally or unintentionally. Something like:

If Activesheet.Name <> wsCurrent.Name then
wsCurrent.Activate
End If

Now that you are back a your starting point, destroy the object variables. It's not absolutely necessary, just good coding practice.

' Recover the Memory
Set wsCurrent = Nothing

You should now be back where you started.

Tuc

Posted by Tuc on June 22, 2001 6:20 AM

Nice catch! I completely overlooked the activate method being called.



Posted by Sean on June 22, 2001 6:27 AM

Perfect! Thanks for the help!