简体   繁体   中英

VBA select another sheet from cell reference in sheet 1

Hoping someone can help (Im a novice so please go easy)

I have a drop down box in cell C11 of Sheet 1.

When I select the option "Unit Sale" from the dropdown box I want to go to the sheet name that is listed in cell M1 of Sheet 1.

Any other selection from the dropdown box should just simply go to Cell A2 of Sheet 1.

I have tried the following from copying some other things on this website but it doesn't seem to work as it wont go to the new sheet.

Thanks Dar

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("C11")) Is Nothing Then
 If Range("C11") = "Unit Sale" Then
      Sheets(Range("M1")).Select
      Range("A2").Select
            Else
        Range("A2").Select
      End If

  End If
End Sub

I find you have to ensure the sheet name is a string. (Btw is there any point to the selecting as it can usually be avoided?)

Private Sub Worksheet_Change(ByVal Target As Range)

If Not Intersect(Target, Range("C11")) Is Nothing Then
    If Target.Value = "Unit Sale" Then
        Application.goto Sheets(Range("M1").Text).Range("A2")
    Else
        Range("A2").Select
    End If
End If

End Sub

in the context of a Worksheet event handler any plain Range reference with no explicit worksheet qualification would implicitly reference the event handler parent worksheet

hence Range("A2").Select would try to select cell A2 in the same worksheet of the event handler, regardless of the preceeding Sheets(Range("M1")).Select , thus generating an error

you could then code as follows:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$C$11" Then Exit Sub

    If Target.Value = "Unit Sale" Then
        With Sheets(Range("M1").Value) 'reference the sheet you want to select cell A2 of
            .Select ' select referenced sheet
            .Range("A2").Select ' select referenced sheet cell A2
        End With
    Else
        Range("A2").Select ' this will always select the parent worksheet cell A2
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM