英文:
Best option for control flow in VBA?
问题
我正在更新一个宏,需要帮助处理控制流。我不是专业的程序员,所以控制流是我之前没有遇到过的东西。
当前版本的宏工作方式如下:
- 检查第一个工作簿中是否存在数据集 A 和 B。如果都没有,则退出。
- 将数据集 A 提取到数组中。
- 将数据集 B 提取到数组中。
- 创建第二个工作簿并进行格式化,然后粘贴数据集 A 和 B。
- 将数据集 C(A 和 B 的月度总和)提取到数组中。
- 创建第三个工作簿并进行格式化,然后粘贴数据集 C。
当前版本仅在 A 和 B 均存在时有效,但我需要它在只有 A 或 B 存在时也能工作。起初,我认为可以复制/粘贴相关部分,然后使用 GoTo 语句跳转到它们,但似乎这是不好的做法。
如何导航处理四种可能的情况的代码?(A+B、都没有、只有 A、只有 B)。为了上下文,我调用一个单独的子程序来创建和格式化第二个和第三个工作簿。
我考虑了这些选项,但不确定哪个更合适:
- GoTo 语句
- Select Case 语句
- 有一个子程序来检查适用于哪种情况,然后调用一个适用情况的单独子程序。
我正在寻找最清晰、最易维护且运行更快的方法(如果差异不可忽略)。我倾向于使用单独的子程序,但首先想在这里确认一下。
英文:
I'm updating a macro and need help with the control flow. I'm not a programmer by trade, so control flow isn't something I've encountered before.
The current version of the macro works as follows:
- Check if datasets A & B are present in 1st workbook. If neither, exit.
- Extract dataset A into arrays.
- Extract dataset B into arrays.
- Create 2nd workbook & format it, then paste datasets A & B.
- Extract dataset C (monthly sum of A & B) into array.
- Create 3rd workbook & format it, then paste dataset C.
The current version only works if both A & B are present, but I need it to work if only either A or B is present. At first I figured I could copy/paste the relevant sections and just skip to them using GoTo statements, but it seems that's bad practice.
How do I navigate the code handling 4 possible scenarios? (A+B, neither, only A, only B). For context, I call a separate sub to create & format the 2nd & 3rd workbooks.
I've considered these options, but unsure which is more appropriate:
- GoTo statements
- Select Case statement
- Have a sub to check for which scenario applies, then call a separate sub for the applicable scenario.
I'm looking for whichever method is cleanest, easiest to maintain, and quicker to run (if the differences aren't negligible). I'm leaning towards separate subs, but wanted to check here first.
答案1
得分: 1
如果我是你,我会创建一个名为“scenario”的变量,并根据你所处的情况为它赋一个值。例如:如果scenario = 1,那么调用(你的A + B情况的过程)。
否则,如果Scenario = 2,那么调用(你的仅A情况的过程等等)。我真的建议避免使用GoTo过程,我认为它们并不是那么有效。
英文:
If I were you I would create a variable "scenario", and I woudl assign it a value depending on the case you are in. Ex : If scenario = 1 then Call (your procedure for case A+B for instance)
Elseif Scenario = 2 then Call (your procedure for case A only etc..). I really recomand to avoid the GoTo procedures which are not that much effective in my opinion.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论