Results 1 to 17 of 17

Thread: [RESOLVED] With Statement (Noob question !!!)

  1. #1

    Thread Starter
    Hyperactive Member DubweiserTM's Avatar
    Join Date
    Dec 2005
    Location
    St-Ferdinand, Québec
    Posts
    427

    Resolved [RESOLVED] With Statement (Noob question !!!)

    Hi everybody !

    Sorry if I take your time for this kind of question...

    I want to know if it's good to use With / End With only for two lines ???

    Something like that:
    Code:
    With txtUser
            .Text = vbNullString
            .Enabled = False
    End With
    Thanks in advance !
    DubweiserTM

    If your question has been answered, you can mark a thread as resolved...

  2. #2
    Fanatic Member
    Join Date
    May 2005
    Posts
    528

    Re: With Statement (Noob question !!!)

    if you are only using it for two lines, i think you will be typing more text to use the with statement than you will have saved
    i think using it for 3 lines will be about the same if you did or didnt use the with statement and you will only start saving typing time if you use it for 4 lines or more.
    so no its not good, below about 3 lines you are only making yourself type more, you only start saving when you use about 4 lines or more.

  3. #3
    Hyperactive Member
    Join Date
    Oct 2001
    Location
    Washington DC
    Posts
    314

    Re: With Statement (Noob question !!!)

    Personally, I have never used "With/End With" and never will.

    I think it is easier to follow code when it is spelled out.
    Code:
    With txtUser
            .Text = vbNullString
            .Enabled = False
    End With
    
    in my opinion obscures the crystal clear
    
    txtUser.Text = vbNullString
    txtUser.Enabled = False
    I wouldn't let the number of characters I have to type influence this decision. Who cares. A quick paste of "txtuser." (one ctrl-V) followed by the variable name.

    Mac

  4. #4
    PowerPoster
    Join Date
    Jun 2001
    Location
    Trafalgar, IN
    Posts
    4,141

    Re: With Statement (Noob question !!!)

    With End With is more efficient.

    If you have
    Code:
     
            txtUser.Text = vbNullString
            txtUser.Enabled = False
    VB is grabbing a reference to the textbox object, setting the text property and then releasing the reference to the textbox. Then VB gets a reference to the textbox again and sets the enabled property of the textbox.


    On the other hand, if you use
    Code:
    With txtUser
            .Text = vbNullString
            .Enabled = False
    End With
    VB grabs a reference to the textbox, sets both properties and then releases the reference.

  5. #5
    PowerPoster
    Join Date
    Feb 2006
    Location
    East of NYC, USA
    Posts
    5,691

    Re: With Statement (Noob question !!!)

    It's also easier to read once you gain a little more experience.
    The most difficult part of developing a program is understanding the problem.
    The second most difficult part is deciding how you're going to solve the problem.
    Actually writing the program (translating your solution into some computer language) is the easiest part.

    Please indent your code and use [HIGHLIGHT="VB"] [/HIGHLIGHT] tags around it to make it easier to read.

    Please Help Us To Save Ana

  6. #6
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: With Statement (Noob question !!!)

    The With...End With construct is the greatest thing since sliced bread. It speeds up your code and increases readability; what's not to love?

    In addition to the execution speed that MarkT explained, it also makes typing the code easier because the intellisense dropdowns kick in.

    Fair warning: Never break out of a With...End With block using a Goto or Exit statement, because VB does not release the object reference. Thus, the following code will generate the "array is locked" runtime error:
    vb Code:
    1. Type MyType
    2.     Text As String
    3. End Type
    4.  
    5. Sub Main()
    6.     Dim MyArray() As MyType
    7.     Dim i As Long
    8.  
    9.     ReDim MyArray(10)
    10.     For i = LBound(MyArray) To UBound(MyArray)
    11.         With MyArray(i)
    12.             If Len(.Text) = 0 Then Exit For
    13.             .Text = LCase(.Text)
    14.         End With
    15.     Next
    16.     ReDim MyArray(5) ' <== Generates runtime error
    17.     Erase MyArray ' <== So does this
    18. End Sub

  7. #7
    Frenzied Member zynder's Avatar
    Join Date
    Nov 2006
    Location
    localhost
    Posts
    1,434

    Re: With Statement (Noob question !!!)

    With two lines of same object i never mind typing it. If more than that, i use with. Readability is not much of an issue as long as it's properly indented.

  8. #8
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: With Statement (Noob question !!!)

    Instead of lines of code, consider number of references. For example:
    vb Code:
    1. With Text1
    2.     .SelStart = 0
    3.     .SelLength = Len(.Text)
    4. End With
    The nice side effect is that the code becomes much more portable. If I rename the textbox, or copy the code to use for a different textbox, I only have to change the name in the code once.

  9. #9

  10. #10
    Hyperactive Member
    Join Date
    Oct 2001
    Location
    Washington DC
    Posts
    314

    Re: With Statement (Noob question !!!)

    Quote Originally Posted by MarkT
    With End With is more efficient.
    Matter of opinion, I guess, but I feel that the "efficiency" gained is so neglibible that it is not worth any consideration at all.

    This button got a difference ranging around 0.03 on a 500mhz machine.
    Code:
    Private Sub Command1_Click()
    Text1.Enabled = False
    Text1.Text = ""
    Text1.Visible = True
    Dim i As Integer
    Dim t As Single, tDif1 As Single, tDif2 As Single
    Const z = 10000 ' loop size
    t = Timer
    For i = 1 To z
      Text1.Enabled = False
      Text1.Text = ""
      Text1.Visible = True
    Next i
    tDif1 = Timer - t
    t = Timer
    For i = 1 To z
      With Text1
        .Enabled = False
        .Text = ""
        .Visible = True
      End With
    Next i
    tDif2 = Timer - t
    Text1.Text = Str$(tDif1 - tDif2)
    End Sub
    Mac

  11. #11
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    33,431

    Re: With Statement (Noob question !!!)

    A timer is not an accurate way of timing code. A more accurate way is described in the Time code using GetTickCount link in my signature. In any case the way you have set up your test isn't really fair since if it were real code the 2nd loop would be set up as

    Code:
    With Text1
        For i = 1 To z
            .Enabled = False
            .Text = ""
            .Visible = True
        Next i
    End With
    and not

    Code:
    For i = 1 To z
      With Text1
        .Enabled = False
        .Text = ""
        .Visible = True
      End With
    Next i
    However, given the .Enabled etc tasks you set up the difference in speed is negligible.

  12. #12
    Hyperactive Member
    Join Date
    Oct 2001
    Location
    Washington DC
    Posts
    314

    Re: With Statement (Noob question !!!)

    Quote Originally Posted by MartinLiss
    isn't really fair
    Well, I disagree with your logic. As we are timing the difference between constructions, my second test is, in fact, fair.

    But many thanks for your timing API info. I ran the code below and got around 20 milliseconds. Namely the same as timer. But I can see that for very accurate needs, the GetTickCount is nicer.

    As you probably agree, the big picture is that no real difference on a 500mhz machine even with 10,000 times. The average program has far fewer instances that could be coded either way. Hence, as I said, efficiency is not a factor. Coding style and clarity can be argued subjectively but there is no objective difference.

    Mac

    Code:
    Option Explicit
    Private Declare Function GetTickCount Lib "kernel32" () As Long
    Private Sub Command1_Click()
    Text1.Enabled = False
    Text1.Text = "Start Test"
    Text1.Visible = True
    Dim i As Integer
    Dim t As Long, tDif1 As Single, tDif2 As Single
    Const z = 10000 ' loop size
    DoEvents
    t = GetTickCount
    For i = 1 To z
      Text1.Enabled = False
      Text1.Text = ""
      Text1.Visible = True
    Next i
    tDif1 = GetTickCount - t
    t = GetTickCount
    For i = 1 To z
      With Text1
        .Enabled = False
        .Text = ""
        .Visible = True
      End With
    Next i
    tDif2 = GetTickCount - t
    Text1.Text = Str$(tDif1 - tDif2)
    End Sub

  13. #13
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: [RESOLVED] With Statement (Noob question !!!)

    Actually it would only be fair comparison if you were using a control array, and accessing different items depending on the loop counter.

    Even tho your loop size is far too small to see any accuracy (so is not valid for comparison!), as you said the speed in that situation is not a factor.

    The efficiency of With can certainly be a factor tho, depending on the situation. Assuming you have code like this:
    Code:
    For x = 1 to 1000
      objExcelApplication.Workbooks("Book1").Sheets("Sheet1").Range("A" & x).Font.Bold = True
      objExcelApplication.Workbooks("Book1").Sheets("Sheet1").Range("A" & x).Font.Underline = True
      objExcelApplication.Workbooks("Book1").Sheets("Sheet1").Range("A" & x).Font.Italic = True
    Next X
    ..it will become noticeably faster (and in most peoples opinion, easier to read) if you change it to this:
    Code:
    For x = 1 to 1000
      With objExcelApplication.Workbooks("Book1").Sheets("Sheet1").Range("A" & x).Font
        .Bold = True
        .Underline = True
        .Italic = True
      End With
    Next X
    ..and faster still if it is converted to this:
    Code:
    With objExcelApplication.Workbooks("Book1").Sheets("Sheet1")
      For x = 1 to 1000
        With .Range("A" & x).Font
          .Bold = True
          .Underline = True
          .Italic = True
        End With
      Next X
    End With
    The reason for this is that each dot is a reference to a sub-object, and it takes time to find the sub-objects (such as .Font). This is even more true in the case of items like Workbooks("Book1"), as a collection needs to be searched each time.

    If this example was simplified to use an object variable for the WorkBook (thus eliminating one child object, and one collection search) the difference would still be noticeable.

  14. #14
    Hyperactive Member
    Join Date
    Oct 2001
    Location
    Washington DC
    Posts
    314

    Re: [RESOLVED] With Statement (Noob question !!!)

    LOL - No doubt.

    If you go back to the top of this thread and follow a bit, you will see we are talking about "ordinary" simple use.

    I'm sure in the case you showed there is great improvement. As there is no way I would ever be doing anything like that, I will forget what you said and someday be coming back here whining "How can I make my application run faster?". At that time, you can have the satisfaction of pointing me to this thread. ROFL.

    So far, my most complicated application runs immediately and I have never experienced other than instant performance on any button click.

    Well, see you in a few years!

    Mac

  15. #15
    PowerPoster
    Join Date
    Feb 2006
    Location
    East of NYC, USA
    Posts
    5,691

    Re: [RESOLVED] With Statement (Noob question !!!)

    Quote Originally Posted by Mr.Mac
    If you go back to the top of this thread and follow a bit, you will see we are talking about "ordinary" simple use.
    Since there's no penalty with even 2 lines, it's a good habit to get into. It also makes it easier if you add more items later (say a grid, and later you want to add formatting for some columns while you're loading it).
    The most difficult part of developing a program is understanding the problem.
    The second most difficult part is deciding how you're going to solve the problem.
    Actually writing the program (translating your solution into some computer language) is the easiest part.

    Please indent your code and use [HIGHLIGHT="VB"] [/HIGHLIGHT] tags around it to make it easier to read.

    Please Help Us To Save Ana

  16. #16
    PowerPoster Ellis Dee's Avatar
    Join Date
    Mar 2007
    Location
    New England
    Posts
    3,530

    Re: With Statement (Noob question !!!)

    Quote Originally Posted by MartinLiss
    A timer is not an accurate way of timing code. A more accurate way is described in the Time code using GetTickCount link in my signature.
    This is apparently not true. To get precision finer than 15.625 milliseconds, use QueryPerformance API.

  17. #17
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    33,431

    Re: With Statement (Noob question !!!)

    Quote Originally Posted by Ellis Dee
    This is apparently not true. To get precision finer than 15.625 milliseconds, use QueryPerformance API.
    GetTickCount is more accurate than a timer which is only accurate to +/50 ms on older operating systems. You are right though in pointing out that it is not the most accurate way. I didn't say that it was and I was aware of the others but chose not to mention them since for most things GetTickCount is sufficient.

Posting Permissions

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



Click Here to Expand Forum to Full Width