Excel-VBA:变量名称、匈牙利表示法和变量命名最佳实践
当我在 Excel-VBA 中编程时,我使用匈牙利表示法。工作表变量以 ws 开头,工作簿变量以 wb 开头等。
当我使用整数时,我总是使用 long,因为过去我已经超过了整数的最大值,并且需要一段时间才能找到 bug - 它更容易只是让所有内容都很长,而不是试图弄清楚变量的值是否有可能超过 32768。
可以用前导 i 而不是 l 来表示这些变量吗,因为我将它们用作整数,即:
dim iStart as long, iEnd as long
我用 n 表示它,而不是
dim lStart as long, lEnd as long
当变量保存某物的数量时,即使它保存的是 long。
dim nObjects as long, nPlots as long
对于哪种表示法使 VBA 最容易阅读,您有什么经验?
When I program in Excel-VBA I use Hungarian notation. Worksheet variables start with ws, workbook variables start wb, etc.
When I use integers, I always use longs, because in the past I have exceeded the maximum value of an integer, and it takes a while to find the bug - it is easier to just make everything a long, rather than trying to figure out if it is ever possible for the value of a variable to exceed 32768.
Is it okay to denote these variables with a leading i instead of l, since I am using them as integers, i.e.:
dim iStart as long, iEnd as long
instead of
dim lStart as long, lEnd as long
When a variable holds the quantity of something, I denote it with an n, even though it is holding a long.
dim nObjects as long, nPlots as long
What is your experience as to which notation makes VBA easiest to read?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
并不真地。保持一致。文档。如果您的团队成长,请考虑您的开发人员同事。
Not really. Be consistent. Document. Consider your fellow developers if your team grows.
匈牙利语更适合反映变量的含义而不是其类型。例如,如果您的程序中有一堆权重,而不是 dblWeightGold、dblWeightSilver 等,只需将它们引用为 wgtGold、wgtSilver。
在类型检查的世界中,在变量名中声明基本类型并不那么重要。我不再以这种方式签署我的变量,并且我在 VBA 中工作。
不过,我会投票支持 GuinnessFan。这是你的约定。只要它是一致的并且有意义,那就没问题。没有一种真正的约定。
Hungarian is better used to reflect the meaning of a variable than its type. For example, if you have a bunch of weights in your program, rather than having dblWeightGold, dblWeightSilver, etc. just cite them as wgtGold, wgtSilver.
In a type-checked world it's not so important to state the fundamental type in the variable name. I no longer sign my variables this way and I do work in VBA.
I will, however, vote up GuinnessFan. It's your convention. As long as it's consistent and makes sense, it'll be fine. There is no one true convention.
我总是以 intVar2、intVar3 或 lngVar4、txtMyTextBox、lblMyLabel 等作为序言...
I always preface with intVar2, intVar3, or lngVar4, txtMyTextBox, lblMyLabel etc...