Restrict VBA to Named Range

  • I have this code, and want to restrict it two 2 named ranges instead of the entire worksheet. What is best way to do this. Not very familiar with VBA.


    Code
    1. Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
    2. ActiveCell.Value = Now()
    3. Application.SendKeys "^{return}"
    4. Target = Format(Time, "h:mm:ss")
    5. Cancel = True







    End Sub

  • Welcome to the Forum. Please read the Forum Rules to understand how the Forum works and why I have added Code Tags to your post


    All VBA code posted in the forum must be wrapped in code tags, which you omitted, including single-line code snippets.Be sure to use them in future posts.


    How to use code tags

    Note: no apostrophe in the tags, just used for demonstration here.

    ['code]


    your code goes between these tags


    ['/code]


    Or, just highlight all of the code and press the <> in the post menu above button to add the code tags.


    Thanks.

  • Sendkeys can be problematic and should be avoided.


    Try this, replace the named ranges in this code with yours

    Code
    1. Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
    2. If Not Intersect(Target, Union(Range("Range1"), Range("Range2"))) Is Nothing Then
    3. Target.value = Now
    4. Application.SendKeys "^{return}"
    5. Target.NumberFormat = "h:mm:ss"
    6. End If
    7. End Sub