07 VBA Best Practices
优质
小牛编辑
148浏览
2023-12-01
- Always have Option Explicit at the top of your code modules to enforce variable declaration.
- Never write procedures and functions that are longer than a full screen as these are hard to understand. Procedures should fit on one screen - ie be 40-50 lines long maximum.- ie be 40-50 lines long maximum.
- Always prefix your variables so you can quickly identify their datatype.
- Never use the Variant datatype unless absolutely necessary.
注:尽量不要使用Variant
,要显示的声明具体的数据类型。Variant是VBA中的一种特殊类型, 所有没有声明的数据类型的变量都默认是Variant型。但Variant型所占的存储空间远大于其他的 数据类型,所以除非必要,否则应该避免申明变量为Variant型。 - Always use the keyword "Call" to call your procedures.
- Always put your arguments in parentheses.
- Never use Global variables unless absolutely necessary. Pass parameters ByVal (ByRef is the default) - only use ByRef where you intend to modify the parameter and pass the change back to the caller.
- Always use tabs to indent your code to bring structure, never use spaces.
- Add "value added" comments which explain why, do not add trivial comments.
- Always add an Error Handler to every procedure and function.
- Use the line continuation character to make your code more readable and to reduce the amount of scrolling.
- Never use the Option Base or Option Compare statements.