使用VBA进行排序操作?
如何使用 VBA 代码执行排序操作?任何定义的宏来执行该操作?
我必须按升序对 B 列进行排序,其中包含值。 C 栏内有日期,并且以最旧到最新的方式排列。
How do I perform a sorting operation using VBA code ? Any defined macros to perform that ?
I have to sort my column B in ascending order which has values in it. And C column which has dates in it and in the fashion oldest to newest.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我强烈建议您使用宏记录器。如果您在 Excel 中没有看到“开发人员”选项卡,请转到 Excel 选项,它应该位于“常用”选项卡中。单击将其打开。
按“录制宏”,然后执行您想做的操作(例如突出显示某一列并按功能区上的“排序”并按升序排序),然后“停止录制”。进入 VBA (Alt+F11) 并查看生成的代码,以了解如何编写相同函数的语法。
例如,对日期进行排序将导致如下结果:
由于在运行宏时您已经选择了要排序的列,因此您可以将代码清理为如下所示:
可以使用相同的代码来完成日期排序,因为它是升序:
诀窍是记住您不需要在已经选择的代码中选择范围。祝你好运,享受录音机的乐趣,它在这种情况下确实很有帮助。
此外,还有很多有关 Excel VBA 的书籍,我建议您在书店或以电子方式购买一本。大多数书籍都会引导您了解 VBA 基础知识、主要关键字、使用记录器,然后最终足够深入,以便您可以编写自己的代码(记录器代码很难优化或完美,但对于学习措辞非常有用) (语法)用于执行一些工作表函数)。
I highly reccomend you play around with the macro recorder. If you do not see a developer tab in your Excel, go to excel options and it should be in the Popular tab. Click to turn it on.
Press Record Macro, then do the thing you want to do (like highlight a column and press Sort on the ribbon and sort by ascending) then Stop Recording. Go into VBA (Alt+F11) and see the resulting code to learn the syntax on how to write the same function.
For example, sort dates will result in something like this:
Since you will already select the column you want to sort when you run your macro, you can clean the code up to something like this:
Sorting dates can be done with the same codes since it's ascending order:
The trick is to remember that you don't need to select the range in the code that you are already selecting. Good luck and have fun with the recorder, it really does help in cases like this.
Also, there are numerous books on Excel VBA and I reccomend you picking one up at the book store or digitally. Most books out there will walk you through the basic of understanding VBA basics, main keywords, using the recorder, then eventually far along enough so you can write your own code (recorder code is hardly optimized or perfect, but is great for learning the wording (syntax) for doing some worksheet functions).