Consulting

Results 1 to 4 of 4

Thread: Simple IF with Worksheet Change Event

  1. #1
    Site Admin
    The Princess
    VBAX Guru Anne Troy's Avatar
    Joined
    May 2004
    Location
    Arlington Heights, IL
    Posts
    2,530
    Location

    Simple IF with Worksheet Change Event

    I know this cannot be the best:


    Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    If Target.Column = 1 Then
    If Target = "payment" Then
    Target.IndentLevel = 1
    Else
    If Target = "credit" Then
    Target.IndentLevel = 1
    End If
    End If
    End If
    End Sub
    How can I make it sweeter?

    (I know that y'all are determined I'm gonna learn VBA.)
    ~Anne Troy

  2. #2
    Administrator
    Chat VP VBAX Guru johnske's Avatar
    Joined
    Jul 2004
    Location
    Townsville, Australia
    Posts
    2,872
    Location
    Hi Anne,

    Probably a better way, but off the top of my head:

    Option Explicit

    Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    If Target.Column = 1 Then
    If Target = "payment" Or Target = "credit" Then Target.IndentLevel = 1
    End If
    End Sub
    EDIT: Just tried the above, it indents for anything in column1 try this instead:

    Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    On Error Resume Next
    If Target.Column = 1 Then
    If Target = "payment" Or Target = "credit" Then
    Target.IndentLevel = 1
    Else
    Target.IndentLevel = 0
    End If
    End If
    End Sub

    Regards,
    John
    You know you're really in trouble when the light at the end of the tunnel turns out to be the headlight of a train hurtling towards you

    The major part of getting the right answer lies in asking the right question...


    Made your code more readable, use VBA tags (this automatically inserts [vba] at the start of your code, and [/vba ] at the end of your code) | Help those helping you by marking your thread solved when it is.

  3. #3
    VBAX Regular
    Joined
    Jul 2004
    Location
    Cambridge, England
    Posts
    23
    Location
    Hey Anne ; it crashed for me anyway ; too many End Ifs? Lately I always try & stick to a couple of principles:

    #1 - Start with

    If Selection.Cells.Count > 1 Then Exit Sub
    (to ward off crashing)

    #2 - cut down on the If ... End If levels by setting all possible parameters ahead. So instead of:

    If Target.Column = 1 Then
    (some code)
    End If
    If Target.Column <> 1 Then Exit Sub
    (some code)
    (no End If)

    HTH,
    Andy

  4. #4
    Site Admin
    The Princess VBAX Guru Anne Troy's Avatar
    Joined
    May 2004
    Location
    Arlington Heights, IL
    Posts
    2,530
    Location
    Oh, so NOW you show up, huh? Hee hee!

    Thanks, guys!
    ~Anne Troy

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •