7 Simple Practices for Writing Super-Readable VBA Code

Sdílet
Vložit
  • čas přidán 19. 07. 2024
  • 👉 Ready to master VBA?
    - Check out my full courses: courses.excelmacromastery.com/
    - Subscribe to the channel here: bit.ly/36hpTCY
    - FREE CHEAT SHEET: Get the free cheat sheet on VBA arrays here: bit.ly/2MXsnz9
    (Note: If the download page doesn't work then make sure to turn off any popup blockers)
    7 Simple Practices for Writing Super-Readable VBA Code
    Having readable code is vital. It makes understanding your code easy to update and easy to understand.
    But most important of it will slash the number of errors in your code. You can waste a lot of time fixing errors so this is very important.
    In this video I show 7 simple techniques that will make your code readable.
    Useful VBA Shortcut Keys:
    Tab: To move lines of code to the right(Indent).
    Shift + Tab: To move lines of code to the left(Outdent).
    Shift + F2: Get the definition of the item under the cursor.
    Ctrl + Shift + F2: Go to the last cursor position.
    Ctrl + Space: AutoComplete Word.
    Alt + F11: Switch between Excel and the VBA Editor.
    Ctrl + R: View the Project Explorer Window.
    Ctrl + Shift + 8(or Ctrl + *): Get the current region on a worksheet.
    F4: View the Properties Window.
    F5: Run the code from the current sub.
    F9(or click left margin): Add a breakpoint to pause the code.

Komentáře • 103

  • @MrDoomfighter
    @MrDoomfighter Před 4 lety +6

    my coworkers will have to thank you :)

  • @RollinShultz
    @RollinShultz Před 4 lety +5

    It serves no one for a programmer to take shortcuts in naming and other tasks to save typing. very descriptive names are essential to good coding. It is also essential to use subroutines to compartmentalize the code for simplicity in making changes and separating concerns.
    It is good to see someone make a video like this for VBA as I get the feeling these things are taken lightly by VBA programmers.

  • @YKazimir
    @YKazimir Před 4 lety +5

    Sir, one of the best Excel youtube channels.

  • @nelsonrioux5555
    @nelsonrioux5555 Před 4 lety +2

    I was able to learn to code by myself but thanking for teaching me best practices. Deeply appreciate it.

  • @mikhailk5690
    @mikhailk5690 Před 4 lety +14

    I didn't know about Enum, this can really make my code much more readable. Thank you so much for sharing these best practices!

    • @Excelmacromastery
      @Excelmacromastery  Před 4 lety

      Glad you like it Mikhail

    • @walerij
      @walerij Před 4 lety

      Why? What is the profit of Enum?

    • @mtotowamungu8259
      @mtotowamungu8259 Před 4 lety

      @@walerij docs.microsoft.com/de-de/office/vba/language/reference/user-interface-help/enum-statement

    • @GGAYTube
      @GGAYTube Před 4 lety

      Yes nice tricks Enum

  • @dangelorrrr
    @dangelorrrr Před 4 lety +3

    Enum - learn something new every time I watch your videos. Thanks, Paul!

  • @szabolcsjobbagy30
    @szabolcsjobbagy30 Před rokem

    Thank you for teaching the developers, these are very important principles.

  • @justinfazzio
    @justinfazzio Před 4 lety +2

    Good stuff! Putting the dim statements within the code rather than at the top was new to me.

  • @BenjaminHouot
    @BenjaminHouot Před 4 lety +13

    I don't use anymore "i" or "j" as a variable. I prefer to use "For Row = 1 to NbRows", Or "For Col = 1 to ..."
    It is more clear.

  • @rods6405
    @rods6405 Před 4 lety

    Been VBAing for 30years did not know about Ctrl+space autocomplete worked on a blank line thanks heaps!
    Have watched many of your videos and have implemented many changes to speed my code up thanks!
    Will watch all your videos now!

  • @FulvioGaggioli
    @FulvioGaggioli Před rokem

    Thank you for your work

  • @RichardCookerly
    @RichardCookerly Před 4 lety

    Just found your channel...loving it! I’ve been a VBA Developer for about 7 years and I learn something from every one of your videos!

  • @xn3ko
    @xn3ko Před 4 lety

    Excelente tips, thank you!

  • @sislmira
    @sislmira Před 4 lety

    Just amazing. Thank you for your videos and page.

  • @wayneedmondson1065
    @wayneedmondson1065 Před 4 lety +1

    Hi Paul.. these are 7 super tips.. really helpful and will implement them right away.. especially declaring variables where I use them and giving variables friendly names. When first learning, it seems correct to mimic what we see others doing.. so.. bad habits get passed through the generations. Thanks for this great advice to chart my own course and develop my own style. Thumbs up!!

    • @Excelmacromastery
      @Excelmacromastery  Před 4 lety

      Thanks very much Wayne. It's true what you say about bad habits being passed.

  • @Mighty1072
    @Mighty1072 Před 4 lety +1

    Very informative. Thanks

  • @grzegorz2852
    @grzegorz2852 Před 2 lety

    Paul, thank u very much for ur videos, they are so super useful. i have learned a lot from u.

  • @grahamparker7729
    @grahamparker7729 Před 4 lety

    Very useful, many thanks 👌🏻

  • @GersonCarhuapoma
    @GersonCarhuapoma Před 4 lety

    Awesome, Paul, like all the time

  • @tuyoexcelypowerbi
    @tuyoexcelypowerbi Před 4 lety +2

    Very useful advices, thanks.

  • @edwardlee9163
    @edwardlee9163 Před 2 lety

    Many thanks, it really helps! Appreciate your anonymous effort.

  • @Excelmacromastery
    @Excelmacromastery  Před 4 lety

    Hi everyone,
    Enjoy your watching and please leave your comments below. Don't forget to press SUBSCRIBE my channel for more videos.
    Thanks for your support.

  • @stevennye5075
    @stevennye5075 Před 4 lety

    very informative!

  • @officetricks6303
    @officetricks6303 Před 2 lety

    Continuously watching your video... Great topics and useful in vba.

  • @psychedelarte7257
    @psychedelarte7257 Před 4 lety

    Thanks for this

  • @mtotowamungu8259
    @mtotowamungu8259 Před 4 lety

    Thank You

  • @rrrprogram8667
    @rrrprogram8667 Před 4 lety

    Beautiful... Loving this channel

  • @rakhisaxena4352
    @rakhisaxena4352 Před 4 lety

    Thank you

  • @Trucpq
    @Trucpq Před 4 lety

    It is valuable knowledge. So useful and so practical. Thanks a lot.

  • @grigull
    @grigull Před 4 lety +1

    A different color for parentheses and array values helps a lot :)

  • @tojtowny
    @tojtowny Před 4 lety

    Still exploring what VBA can offer and how to use it, but deffinitly this makes the jurney easier :)

  • @kuldar.
    @kuldar. Před 3 lety

    Thank you, your tips are really helpful!

  • @danielszalok8540
    @danielszalok8540 Před 4 lety

    Thanks, now I understand why enum is better than constants in this special case! 🙂 A question: do you think 'With-End Width' helps readability? I use it very frequently, but it's so easy to overuse it. How about the readability of if, select case and iif? I would love to watch a video about this 🙂

  • @rrrraaaacccc80
    @rrrraaaacccc80 Před 5 měsíci

    Great 💯👍

  • @Akens888
    @Akens888 Před 4 lety +4

    I prefer to use i,o,p for nested loops. j looks too much like i and i,o,p are right next to each other.
    Great video.

    • @TP-om8of
      @TP-om8of Před rokem

      I don’t like i and j either. I use k and l.

  • @houstonvanhoy2198
    @houstonvanhoy2198 Před 3 lety +1

    6:41. Magic numbers, leading into demonstration of ENUMS.

  • @bestscenes1469
    @bestscenes1469 Před 4 lety

    You're always awesome. Very useful video

  • @joecortizo
    @joecortizo Před 4 lety

    People sometimes underestimate the power of a macro...
    Thanks Master!

  • @trevorclack7178
    @trevorclack7178 Před 4 lety +2

    You can get a speed up in code execution by using full referencing as well (e.g. .shData.Range or VBA.Instr). I would also suggest having a unique name for all you VBA projects rather then using the default project name "VBAProject" in order to reduce errors if multiple projects are running at the same time.

  • @teguhmarwanto7645
    @teguhmarwanto7645 Před 4 lety

    Its very good videos. Simple and clear

  • @oceanic14123
    @oceanic14123 Před 4 lety

    Great tutorial, thank you. I have a question regarding code behind userforms. I have Textbox, ListBox, ComboBox...with Click events, Functions, BeforeUpdate event, AfterUpdate event and Change event, the code is a mile long and disorganized. Is it possible separate, organize the code by Click event, Function, Update event in regular modules?

  • @Inexpugnablement
    @Inexpugnablement Před 4 lety +3

    Thanks for your vids so interesting and useful !
    If I dared, I'd suggest you an eighth: comments. It's so obvious but so necessary.

  • @Anomander1
    @Anomander1 Před 4 lety +1

    Every vid from you is nice, thank you.
    I would not delcare variables when you need them, but declare them when you are at the top of your sub or Function. this makes it much easier to transition to another programming language where defining the variables at the beginning is mandatory.

  • @DarcyWhyte
    @DarcyWhyte Před 4 lety +1

    Lover your videos. Quick question, when you click it makes little circles. Is that done in post processing or do you have a program that does that in real time?

  • @KcKc-bh6lu
    @KcKc-bh6lu Před 4 lety

    Your suggestion is pretty good practice of variable declaration for VBA because of its interpreter nature. But in compiling languages, declaration must be predefined before any use.

    • @Excelmacromastery
      @Excelmacromastery  Před 4 lety

      I'm not sure what you mean. You can define variables as you use them in C# and C++.

  • @JimHenderson19
    @JimHenderson19 Před 3 lety

    I really have learned much from watching your videos.

  • @ferreira8822
    @ferreira8822 Před 4 lety

    Great

  • @urielramirez27
    @urielramirez27 Před 4 lety

    Very simple and powerful tips, thank you. Which software you use to record your tutorials?

  • @davidr5847
    @davidr5847 Před 4 lety

    I really love your videos. I always considered myself a pro in VBA, but after seeing some videos of you I'm not that sure any more lol. However, sometimes I need to make trainingvideos myself for coworkers, what is the software you use for those red boxes to point out certain parts in the screen? I use Camtasia but I haven't found this feature.. Have a great day

    • @Excelmacromastery
      @Excelmacromastery  Před 4 lety +1

      They are under Annotations in camtasia.

    • @davidr5847
      @davidr5847 Před 4 lety

      @@Excelmacromastery Cannot believe I missed that. Thanks!

  • @KhalilYasser
    @KhalilYasser Před 4 lety

    Thanks a lot for the awesome hints

  • @cigmorfil4101
    @cigmorfil4101 Před 4 lety +2

    The use of I, J etc for loops is a remnant of Fortran where all variables starting with I to N are integers and the rest are floating point (unless explicitly declared). For a loop it would be done an exact number of times so integers would be used for the counter - if a floating point variable was used due to rounding the loop may be executed an extra time.

    • @gabiold
      @gabiold Před 4 lety

      I always thought "I" just stands for "index"...

    • @Excelmacromastery
      @Excelmacromastery  Před 4 lety

      Thanks for the info😀

    • @dominiquenoel939
      @dominiquenoel939 Před 4 lety

      In my case, first variable use in for-next loop if always "F" because in ZX81 / ZX spectrum it was same key: first push F to type "For" directly and second push for variable = F is more quickly.

    • @Excelmacromastery
      @Excelmacromastery  Před 4 lety +1

      That's a good reason. My spectrum was the +2 with a whopping 128k .

  • @anthonycroft7538
    @anthonycroft7538 Před 4 lety +1

    Good stuff Paul, although the variable dimming in the body vs top of the procedure would be at the Brexit level of contentiousness within our profession.

  • @hotflashfoto
    @hotflashfoto Před rokem

    I agree with your reasoning, but I don't use your execution regarding the declaration of variables. I use the top of the module to declare mine, grouping strings onto one or more lines, as well as other variable types. I also use the LNC, or a modified version of it, to add the type of variable to the front of the name and then supply a descriptive name.
    For example:
    Const cstrErrTitle as String = "ERROR MESSAGE TITLE HERE"
    Private wsMacro as Worksheet, wsSource as Worksheet, wsDest as Worksheet
    Private strName as String, strAddress1 as String
    Private lngCount as Long
    I do this instead of using Dim within each Sub, mostly because I want the value to travel as it's being used, rather than using it only within the Sub and then disposing of it.
    While I understand the purpose of declaring immediately before use, and it makes it easier to share the code, it also clutters up the code and restricts using the variable's value to that Sub only.
    I'm sure we won't see eye-to-eye on this, and I don't feel like you're teaching anything that needs to be corrected. It's just that the style of coding that I use is different.

  • @Laxmanmane007
    @Laxmanmane007 Před 4 lety

    Also make video on power bi

  • @dougtvedt890
    @dougtvedt890 Před 3 lety

    At 8:52 when using variables instead of cell references in a For/Next loop, should they be re-set back to 0 before iterating to the next i?

  • @maciejdolinski1036
    @maciejdolinski1036 Před 4 lety

    Hi Paul,
    Thank you for great advises! Anyway, I wonder, why Enum is better than Constants? I used constants so far. Can you please comment?

    • @Excelmacromastery
      @Excelmacromastery  Před 4 lety

      1. You can group related constants using Enum.
      2. You can use the enum as a type once you have created it. e.g. set it as a parameter type.
      3. Intellisense shows all the available options when you use the enum in your code.

  • @lolguy-x9n
    @lolguy-x9n Před 4 lety +10

    I prefer variables at top not as I use. that way I k ow where to get tbem

  • @rods6405
    @rods6405 Před 4 lety +2

    I avoid using I and L in code and in excel they look to much like each other and 1 in certain fonts. Test which the lowercase L or I in text I l ? even google font is hard to tell. For for loops I use XA XB XC etc

  • @dimonovych
    @dimonovych Před 4 lety

    There is Smart Indenter for VBA, which makes your code Indented by only clicking one button.
    Really convenient.

  • @KevD_
    @KevD_ Před 4 lety +1

    I did not know that there was a checkbox in the settings to insist that all variables be declared. The first thing I have done for years, before starting a new module is type "OPTION EXPLICIT". I don't even understand why you are allowed to not declare variables!
    Shakes fist at Microsoft.

  • @MrWarlls
    @MrWarlls Před 4 lety

    I prefer to declare the variables on the top of the function/sub. I think it is easier to find them. I am used to start all my variables that have the same type with the same letter (s for the string, a for the arrays, l for long...) For me, it is a good way to identify the king of variable without looking for the statement.

    • @Excelmacromastery
      @Excelmacromastery  Před 4 lety

      The variable naming you are referring to is Hungarian Notation which was used a lot in the 1990s and before.

  • @igalbitan5096
    @igalbitan5096 Před 4 lety

    Isn't there any tool to indent code automatically?

  • @TP-om8of
    @TP-om8of Před rokem

    I don’t indent my code, I exdent it.

  • @airegun9987
    @airegun9987 Před 4 lety

    Whatever benefit there may be to declaring variables at the point of use is far outweighed by the abject clutter that it creates...

  • @serdip
    @serdip Před 4 lety

    Great video, as always.
    I disagree, respectfully, with the practice of declaring variables immediately before they're used because in some cases it will be necessary to create more variables than would actually be needed if the declarations were centralized at the top of the method.
    Below is an admittedly contrived example that illustrates why one cannot always declare variables immediately before they're used.
    ===============================================================
    Public Sub TestCode()
    'Purpose: If current weekday is Monday, print weekday names
    'excluding Monday, in ascending order by weekday number
    'If current weekday is NOT Monday, print weekday names
    'in DESCENDING order by weekday number
    'Cannot always declare variables immediately before
    'they're used
    Dim blnIsMonday As Boolean
    blnIsMonday = (Weekday(Date) = vbMonday)
    If blnIsMonday Then
    Dim i As Integer
    For i = vbSunday To vbSaturday
    If i vbMonday Then Debug.Print WeekdayName(i)
    Next i
    Else
    'Dim i As Integer '

    • @Excelmacromastery
      @Excelmacromastery  Před 4 lety

      Thanks for your comment. If you need extra variables then you code needs to be rewritten.
      In your example, the 2 for loops are not necessary. You can write the code so only one is required by using a variable for the start, end and step values.
      Then you only need one For loop no matter how many conditions.

  • @candeffect
    @candeffect Před 4 lety

    Indenting under Sub is more annoying than helpful.