How to avoid using .Select, .Activate, ActiveSheet,ActiveCell in my specific vba code?

后端 未结 3 1934
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 10:49

I have this code that obviously use Select, .Activate,...and I understand it\'s not a good practice in addition the application is craching now and then so thats probably be

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-20 11:18

    Select and Activate are basically just methods that are used in recording macros. To trim down a macro from there, you can do the following:

    • Anywhere ActiveCell is used, simply replace it with the Range reference that .Activate was called on. (In your case, the first With ActiveCell.Font would become With Sheets("A4").Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) - 2, BoxColOffset(Box)).Font)
    • Anywhere Selection is used, simply replace it with the Range reference that .Select was called on. (In your case, With Selection would become With Range(Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 1, 1 + BoxColOffset(Box) + 1), Cells(1 + PageRowOffset(Page) + BoxRowOffset(Box) + 2, 1 + BoxColOffset(Box) + 1)))

    As an aside, when you correct that last With Selection block, you'll be able to move the .NumberFormat adjustment into the With block as well.

    Some additional advice would be to get in the habit of establishing Worksheet objects that you can store the specific sheets your working in. So I would do something like Dim currentSheet As Worksheet and then somewhere before this block of code you've posted (where appropriate) Set currentSheet = Sheets("A4"). You'll have to update any Range(...) and Cells(...) calls to be currentSheet.Range(...), but the advantage of this is that your Range and Cells calls will always reference Sheets("A4") -- they won't accidentally switch context if you make modifications to this macro later on. This is how you also avoid relying on ActiveSheet, in general.

提交回复
热议问题