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
    Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
    ActiveCell.Value = Now()
    Application.SendKeys "^{return}"
    
    
    Target = Format(Time, "h:mm:ss")
    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
    Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
    If Not Intersect(Target, Union(Range("Range1"), Range("Range2"))) Is Nothing Then
    Target.value = Now
    Application.SendKeys "^{return}"
    Target.NumberFormat = "h:mm:ss"
    End If
    End Sub

Participate now!

Don’t have an account yet? Register yourself now and be a part of our community!