Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

vba - In Excel, updating a formula seems to trigger an unrelated private sub on the same worksheet. How can I get this to stop?

I've created a drop down menu through data validation for workbook navigation. The following is a snippet of code I have for the drop down box to change worksheets in the workbook:

Private Sub Worksheet_Change(ByVal Target As Range)
   On Error Resume Next
    If Not (Application.Intersect(Range("J4"), Target) Is Nothing) Then _
        ThisWorkbook.Sheets("Home").Visible = False
        ThisWorkbook.Sheets(Target.Value).Activate
        ThisWorkbook.Sheets(Target.Value).Visible = True
        ThisWorkbook.Sheets("Imported Data").Visible = False
End Sub

The code is meant to hide all other worksheets that are accessible by the drop down list besides the one selected. I have about 10 tabs and this code has worked perfectly to achieve the basic goal of navigation. However, some pages have formulas and when you update data in the cells meant for calculations the workbook jumps to a random worksheet in the workbook that is not at all referenced in this sub.

Is there some way to have my worksheets not try to do anything with this sub unless the dropdown menu itself is changed?

Bonus (less important) Question: is there a way to make the drop box default to (blank) unless the menu itself is accessed?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Then _

  1. The space followed by an underscore _ means that the current statement isn't finished yet but continues on the next line. Right now the last 3 lines will run whenever there is a change in the worksheet. Put the entire code in If-Endif.

  2. Also avoid unnecessary use of On Error Resume Next. Use proper error handling.

  3. You need to make the sheet visible before you activate it and not vice versa.

Try this

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo Whoa
    
    If Not (Application.Intersect(Range("J4"), Target) Is Nothing) Then
        ThisWorkbook.Sheets("Home").Visible = False
        
        ThisWorkbook.Sheets(Target.Value).Visible = True
        ThisWorkbook.Sheets(Target.Value).Activate
        
        ThisWorkbook.Sheets("Imported Data").Visible = False
    End If
    
Letscontinue:
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

is there a way to make the drop box default to (blank) unless the menu itself is accessed?

If you have created it with Data Valdation then insert a blank value in the list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...