简体   繁体   English

VBA从工作表1中的单元格引用中选择另一个工作表

[英]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. 我在工作表1的单元格C11中有一个下拉框。

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. 当我从下拉框中选择选项“单位销售”时,我要转到工作表1的单元格M1中列出的工作表名称。

Any other selection from the dropdown box should just simply go to Cell A2 of Sheet 1. 下拉框中的任何其他选择都应直接转到工作表1的单元格A2。

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 Worksheet事件处理程序的上下文中,没有明确的工作表限定的任何普通 Range引用都将隐式引用事件处理程序的父工作表

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 因此, Range("A2").Select会尝试在事件处理程序的同一工作表中选择单元格A2,而不管前面的Sheets(Range("M1")).Select为何,从而生成错误

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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