What is cyclomatic complexity?

"Think of cyclomatic complexity as a measure of the number of pathways through a piece of code."  

-Mark Seemann, "Code That Fits in Your Head"

To calculate the cyclomatic complexity of a VBA procedure, start at 1 then add 1 for each of the following statements:

  • If
  • Else If
  • Else
  • Case
  • For...Next
  • For Each...Next
  • Do...Loop
  • While...Wend
  • GoSub...Return
  • GoTo

And add 1 for each of these functions:

  • IIf
  • Nz
  • Choose (+1 for each choice)
  • Switch (+1 for each expr-value pair)

To write code that "fits in your brain," Seemann recommends limiting cyclomatic complexity to 7.

Cover image created with Microsoft Designer