VBA enums give occasional “Constant Expression Required” errors

后端 未结 5 1158
忘掉有多难
忘掉有多难 2020-12-16 11:41

I\'m using an enum defined in a class module in Excel VBA. This has been working fine, but I\'ve started getting a compile error on every time I do a comparison on enum vari

相关标签:
5条回答
  • 2020-12-16 11:55

    This error does now and then, when no changes were made to the enum or its use or any code related. What worked for me is to make the move the enum from the Class to a Module I have called 'Common' and make the enum Public instead of Private.

    0 讨论(0)
  • 2020-12-16 12:01

    As noted in the question, I got rid of the error by editing and saving the enum definition, then undoing the edit and saving again. Having recently done some more work on the project, I found a different but similar issue - one line of code would give a "Type mismatch" error, where there was no type mismatch and where the same function, unchanged, had been working fine with the same inputs.

    Some of the intermittent errors I'm seeing might be due to a buildup of code artefacts in the Excel file - having done some reading, I've found that VBA code gets compiled and saved into the file. There's no "clean" or "rebuild all" option - VBA tries to work out for itself what incremental changes are needed. This can lead to all kinds of odd runtime behaviour in projects where you've made lots of code changes. This is likely the cause of the enum errors I was finding during initial development of this workbook. The section "What It Means to Decompile and Compact in VBA" in this article gives a good overview.

    Most mentions of this problem recommend using VBA CodeCleaner: http://www.appspro.com/Utilities/CodeCleaner.htm. Chip Pearson, a well-known and respected VBA expert, says " I very strongly recommend this add-in". I'm surprised I haven't come across this before!

    0 讨论(0)
  • 2020-12-16 12:02

    Seems to be a bug.

    Copy the same module's code to a new one, and recompile. That seems to solve it for some.

    A similar fix exists, which involves editing and undoing on the enum definition's line.

    Consider switching to numeric constants if this is a frequent problem.

    0 讨论(0)
  • 2020-12-16 12:07

    I had the same issue with my Enum, I added Public Enum to the declaration and the problem stopped. No need to reboot.

    0 讨论(0)
  • 2020-12-16 12:18

    An old question but just experienced this. Removed Public definer on the Enum and it compiled just fine. Didn't restart IDE. Surprising this is still here.

    0 讨论(0)
提交回复
热议问题