vb6parse 1.0.1

vb6parse is a library for parsing and analyzing VB6 code, from projects, to controls, to modules, and forms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
//! # `IRR` Function
//!
//! Returns a `Double` specifying the internal rate of return for a series of periodic cash flows (payments and receipts).
//!
//! ## Syntax
//!
//! ```vb
//! IRR(values()[, guess])
//! ```
//!
//! ## Parameters
//!
//! - `values()` (Required): `Array` of `Double` specifying cash flow values. The array must contain at least one positive value (receipt) and one negative value (payment)
//! - `guess` (Optional): `Variant` specifying value you estimate will be returned by `IRR`. If omitted, guess is 0.1 (10 percent)
//!
//! ## Return Value
//!
//! Returns a `Double` representing the internal rate of return:
//! - Expressed as a decimal (0.1 = 10%)
//! - The discount rate that makes the net present value (`NPV`) of all cash flows equal to zero
//! - Used to evaluate the profitability of potential investments
//! - Higher `IRR` indicates more desirable investment
//!
//! ## Remarks
//!
//! The internal rate of return is the interest rate received for an investment consisting of payments and receipts that occur at regular intervals:
//!
//! - `IRR` uses the order of values within the array to interpret the order of cash flows
//! - Cash flows must occur at regular intervals (monthly, quarterly, annually, etc.)
//! - First element is typically a negative value (initial investment)
//! - Array must contain at least one positive and one negative value
//! - Uses an iterative technique to calculate `IRR`
//! - Begins with the value of `guess` and cycles through until result is accurate to within 0.00001 percent
//! - If `IRR` can't find a result after 20 tries, it fails with Error 5
//! - Most cases, you don't need to provide `guess`; if omitted, 10% is assumed
//! - If `IRR` returns Error 5, try different value for `guess`
//! - `IRR` is closely related to `NPV` (net present value) function
//! - `IRR` is the rate where `NPV` equals zero: `NPV(IRR(values), values) = 0` (approximately)
//!
//! ## Typical Uses
//!
//! 1. **Investment Analysis**: Evaluate profitability of potential investments
//! 2. **Project Evaluation**: Compare multiple projects to select most profitable
//! 3. **Capital Budgeting**: Assess capital expenditure decisions
//! 4. **Business Case Analysis**: Justify business investments with `ROI` calculations
//! 5. **Equipment Purchase**: Evaluate cost savings from new equipment
//! 6. **Real Estate Investment**: Analyze property investment returns
//! 7. **Lease vs Buy**: Compare financial impact of leasing versus purchasing
//! 8. **Portfolio Management**: Assess historical returns on investments
//!
//! ## Basic Usage Examples
//!
//! ```vb
//! ' Example 1: Simple investment analysis
//! Dim cashFlows(0 To 4) As Double
//! Dim returnRate As Double
//!
//! cashFlows(0) = -10000  ' Initial investment (negative = cash out)
//! cashFlows(1) = 3000    ' Year 1 return
//! cashFlows(2) = 3500    ' Year 2 return
//! cashFlows(3) = 4000    ' Year 3 return
//! cashFlows(4) = 4500    ' Year 4 return
//!
//! returnRate = IRR(cashFlows)
//! Debug.Print "Internal Rate of Return: " & Format$(returnRate * 100, "0.00") & "%"
//! ' Prints approximately: 28.09%
//!
//! ' Example 2: Equipment purchase evaluation
//! Dim equipmentCosts(0 To 5) As Double
//! equipmentCosts(0) = -50000  ' Equipment cost
//! equipmentCosts(1) = 12000   ' Year 1 savings
//! equipmentCosts(2) = 15000   ' Year 2 savings
//! equipmentCosts(3) = 18000   ' Year 3 savings
//! equipmentCosts(4) = 21000   ' Year 4 savings
//! equipmentCosts(5) = 24000   ' Year 5 savings
//!
//! returnRate = IRR(equipmentCosts)
//! If returnRate > 0.15 Then  ' 15% hurdle rate
//!     MsgBox "Equipment purchase approved - IRR: " & Format$(returnRate * 100, "0.00") & "%"
//! Else
//!     MsgBox "Equipment purchase rejected - IRR too low"
//! End If
//!
//! ' Example 3: Comparing two projects
//! Dim projectA(0 To 3) As Double
//! Dim projectB(0 To 3) As Double
//!
//! projectA(0) = -25000: projectA(1) = 10000: projectA(2) = 12000: projectA(3) = 15000
//! projectB(0) = -30000: projectB(1) = 15000: projectB(2) = 14000: projectB(3) = 13000
//!
//! Dim irrA As Double, irrB As Double
//! irrA = IRR(projectA)
//! irrB = IRR(projectB)
//!
//! Debug.Print "Project A IRR: " & Format$(irrA * 100, "0.00") & "%"
//! Debug.Print "Project B IRR: " & Format$(irrB * 100, "0.00") & "%"
//!
//! If irrA > irrB Then
//!     MsgBox "Select Project A"
//! Else
//!     MsgBox "Select Project B"
//! End If
//!
//! ' Example 4: Using guess parameter for difficult calculations
//! Dim complexFlows(0 To 6) As Double
//! complexFlows(0) = -100000
//! complexFlows(1) = -50000   ' Additional investment in year 2
//! complexFlows(2) = 20000
//! complexFlows(3) = 40000
//! complexFlows(4) = 50000
//! complexFlows(5) = 60000
//! complexFlows(6) = 70000
//!
//! ' Provide guess to help convergence
//! On Error Resume Next
//! returnRate = IRR(complexFlows, 0.2)  ' Start with 20% guess
//! If Err.Number = 0 Then
//!     Debug.Print "Complex IRR: " & Format$(returnRate * 100, "0.00") & "%"
//! Else
//!     Debug.Print "Could not calculate IRR"
//! End If
//! On Error GoTo 0
//! ```
//!
//! ## Common Patterns
//!
//! ```vb
//! ' Pattern 1: Calculate IRR for investment
//! Function CalculateInvestmentIRR(initialInvestment As Double, returns() As Double) As Double
//!     Dim cashFlows() As Double
//!     Dim i As Integer
//!     
//!     ReDim cashFlows(0 To UBound(returns) + 1)
//!     cashFlows(0) = -Abs(initialInvestment)  ' Ensure negative
//!     
//!     For i = 0 To UBound(returns)
//!         cashFlows(i + 1) = returns(i)
//!     Next i
//!     
//!     CalculateInvestmentIRR = IRR(cashFlows)
//! End Function
//!
//! ' Pattern 2: IRR with hurdle rate comparison
//! Function MeetsHurdleRate(cashFlows() As Double, hurdleRate As Double) As Boolean
//!     On Error Resume Next
//!     Dim rate As Double
//!     rate = IRR(cashFlows)
//!     
//!     If Err.Number = 0 Then
//!         MeetsHurdleRate = (rate >= hurdleRate)
//!     Else
//!         MeetsHurdleRate = False
//!     End If
//!     On Error GoTo 0
//! End Function
//!
//! ' Pattern 3: Format IRR as percentage
//! Function FormatIRR(cashFlows() As Double) As String
//!     On Error Resume Next
//!     Dim rate As Double
//!     rate = IRR(cashFlows)
//!     
//!     If Err.Number = 0 Then
//!         FormatIRR = Format$(rate * 100, "0.00") & "%"
//!     Else
//!         FormatIRR = "N/A"
//!     End If
//!     On Error GoTo 0
//! End Function
//!
//! ' Pattern 4: Select best investment from multiple options
//! Function SelectBestInvestment(investments As Collection) As Integer
//!     Dim bestIRR As Double
//!     Dim bestIndex As Integer
//!     Dim currentIRR As Double
//!     Dim i As Integer
//!     
//!     bestIRR = -999999
//!     bestIndex = -1
//!     
//!     For i = 1 To investments.Count
//!         On Error Resume Next
//!         currentIRR = IRR(investments(i))
//!         
//!         If Err.Number = 0 And currentIRR > bestIRR Then
//!             bestIRR = currentIRR
//!             bestIndex = i
//!         End If
//!         On Error GoTo 0
//!     Next i
//!     
//!     SelectBestInvestment = bestIndex
//! End Function
//!
//! ' Pattern 5: Calculate IRR with validation
//! Function SafeIRR(cashFlows() As Double, Optional guess As Double = 0.1) As Variant
//!     Dim hasPositive As Boolean
//!     Dim hasNegative As Boolean
//!     Dim i As Integer
//!     
//!     ' Validate array has both positive and negative values
//!     For i = LBound(cashFlows) To UBound(cashFlows)
//!         If cashFlows(i) > 0 Then hasPositive = True
//!         If cashFlows(i) < 0 Then hasNegative = True
//!     Next i
//!     
//!     If Not (hasPositive And hasNegative) Then
//!         SafeIRR = Null
//!         Exit Function
//!     End If
//!     
//!     On Error Resume Next
//!     SafeIRR = IRR(cashFlows, guess)
//!     If Err.Number <> 0 Then SafeIRR = Null
//!     On Error GoTo 0
//! End Function
//!
//! ' Pattern 6: Compare project IRRs
//! Sub CompareProjects(project1() As Double, project2() As Double)
//!     Dim irr1 As Double, irr2 As Double
//!     
//!     irr1 = IRR(project1)
//!     irr2 = IRR(project2)
//!     
//!     Debug.Print "Project 1 IRR: " & Format$(irr1 * 100, "0.00") & "%"
//!     Debug.Print "Project 2 IRR: " & Format$(irr2 * 100, "0.00") & "%"
//!     Debug.Print "Difference: " & Format$((irr1 - irr2) * 100, "0.00") & " percentage points"
//! End Sub
//!
//! ' Pattern 7: Calculate breakeven IRR
//! Function GetBreakevenIRR(costOfCapital As Double, cashFlows() As Double) As String
//!     Dim projectIRR As Double
//!     projectIRR = IRR(cashFlows)
//!     
//!     If projectIRR > costOfCapital Then
//!         GetBreakevenIRR = "Project exceeds cost of capital by " & _
//!                          Format$((projectIRR - costOfCapital) * 100, "0.00") & "%"
//!     ElseIf projectIRR < costOfCapital Then
//!         GetBreakevenIRR = "Project falls short of cost of capital by " & _
//!                          Format$((costOfCapital - projectIRR) * 100, "0.00") & "%"
//!     Else
//!         GetBreakevenIRR = "Project exactly meets cost of capital"
//!     End If
//! End Function
//!
//! ' Pattern 8: IRR for monthly cash flows
//! Function MonthlyIRR(monthlyCashFlows() As Double) As Double
//!     ' Returns annualized IRR from monthly cash flows
//!     Dim monthlyRate As Double
//!     monthlyRate = IRR(monthlyCashFlows)
//!     MonthlyIRR = ((1 + monthlyRate) ^ 12) - 1  ' Convert to annual rate
//! End Function
//!
//! ' Pattern 9: Try multiple guesses if IRR fails
//! Function RobustIRR(cashFlows() As Double) As Variant
//!     Dim guesses As Variant
//!     Dim i As Integer
//!     Dim result As Double
//!     
//!     guesses = Array(0.1, 0.2, 0.5, -0.1, -0.2, 0.01, 0.9)
//!     
//!     For i = 0 To UBound(guesses)
//!         On Error Resume Next
//!         result = IRR(cashFlows, guesses(i))
//!         
//!         If Err.Number = 0 Then
//!             RobustIRR = result
//!             On Error GoTo 0
//!             Exit Function
//!         End If
//!         On Error GoTo 0
//!     Next i
//!     
//!     RobustIRR = Null  ' Could not calculate
//! End Function
//!
//! ' Pattern 10: Incremental IRR analysis
//! Function IncrementalIRR(baseProject() As Double, incrementalProject() As Double) As Double
//!     Dim incrementalFlows() As Double
//!     Dim i As Integer
//!     Dim maxIndex As Integer
//!     
//!     ' Calculate incremental cash flows
//!     maxIndex = IIf(UBound(baseProject) > UBound(incrementalProject), _
//!                    UBound(baseProject), UBound(incrementalProject))
//!     
//!     ReDim incrementalFlows(0 To maxIndex)
//!     
//!     For i = 0 To maxIndex
//!         incrementalFlows(i) = 0
//!         If i <= UBound(incrementalProject) Then
//!             incrementalFlows(i) = incrementalFlows(i) + incrementalProject(i)
//!         End If
//!         If i <= UBound(baseProject) Then
//!             incrementalFlows(i) = incrementalFlows(i) - baseProject(i)
//!         End If
//!     Next i
//!     
//!     IncrementalIRR = IRR(incrementalFlows)
//! End Function
//! ```
//!
//! ## Advanced Usage Examples
//!
//! ```vb
//! ' Example 1: Investment analyzer class
//! Public Class InvestmentAnalyzer
//!     Private m_cashFlows() As Double
//!     Private m_irr As Variant
//!     Private m_calculated As Boolean
//!     
//!     Public Sub SetCashFlows(cashFlows() As Double)
//!         Dim i As Integer
//!         ReDim m_cashFlows(LBound(cashFlows) To UBound(cashFlows))
//!         
//!         For i = LBound(cashFlows) To UBound(cashFlows)
//!             m_cashFlows(i) = cashFlows(i)
//!         Next i
//!         
//!         m_calculated = False
//!     End Sub
//!     
//!     Public Function GetIRR() As Variant
//!         If Not m_calculated Then
//!             On Error Resume Next
//!             m_irr = IRR(m_cashFlows)
//!             If Err.Number <> 0 Then m_irr = Null
//!             On Error GoTo 0
//!             m_calculated = True
//!         End If
//!         GetIRR = m_irr
//!     End Function
//!     
//!     Public Function GetFormattedIRR() As String
//!         Dim rate As Variant
//!         rate = GetIRR()
//!         
//!         If IsNull(rate) Then
//!             GetFormattedIRR = "N/A"
//!         Else
//!             GetFormattedIRR = Format$(rate * 100, "0.00") & "%"
//!         End If
//!     End Function
//!     
//!     Public Function IsAcceptable(hurdleRate As Double) As Boolean
//!         Dim rate As Variant
//!         rate = GetIRR()
//!         
//!         If IsNull(rate) Then
//!             IsAcceptable = False
//!         Else
//!             IsAcceptable = (rate >= hurdleRate)
//!         End If
//!     End Function
//!     
//!     Public Function CompareToRate(targetRate As Double) As String
//!         Dim rate As Variant
//!         rate = GetIRR()
//!         
//!         If IsNull(rate) Then
//!             CompareToRate = "Unable to calculate IRR"
//!         ElseIf rate > targetRate Then
//!             CompareToRate = "Exceeds target by " & _
//!                            Format$((rate - targetRate) * 100, "0.00") & "%"
//!         ElseIf rate < targetRate Then
//!             CompareToRate = "Below target by " & _
//!                            Format$((targetRate - rate) * 100, "0.00") & "%"
//!         Else
//!             CompareToRate = "Exactly meets target"
//!         End If
//!     End Function
//! End Class
//!
//! ' Example 2: Project portfolio manager
//! Public Class ProjectPortfolio
//!     Private m_projects As Collection
//!     
//!     Private Sub Class_Initialize()
//!         Set m_projects = New Collection
//!     End Sub
//!     
//!     Public Sub AddProject(projectName As String, cashFlows() As Double)
//!         Dim projectData As Variant
//!         projectData = Array(projectName, cashFlows)
//!         m_projects.Add projectData
//!     End Sub
//!     
//!     Public Function GetBestProject() As String
//!         Dim bestIRR As Double
//!         Dim bestName As String
//!         Dim currentIRR As Double
//!         Dim i As Integer
//!         Dim projectData As Variant
//!         
//!         bestIRR = -999999
//!         bestName = ""
//!         
//!         For i = 1 To m_projects.Count
//!             projectData = m_projects(i)
//!             
//!             On Error Resume Next
//!             currentIRR = IRR(projectData(1))
//!             
//!             If Err.Number = 0 And currentIRR > bestIRR Then
//!                 bestIRR = currentIRR
//!                 bestName = projectData(0)
//!             End If
//!             On Error GoTo 0
//!         Next i
//!         
//!         GetBestProject = bestName & " (IRR: " & Format$(bestIRR * 100, "0.00") & "%)"
//!     End Function
//!     
//!     Public Function GetRankedProjects() As String
//!         Dim rankings() As Variant
//!         Dim i As Integer, j As Integer
//!         Dim temp As Variant
//!         Dim result As String
//!         Dim projectData As Variant
//!         Dim projectIRR As Double
//!         
//!         ReDim rankings(1 To m_projects.Count)
//!         
//!         ' Build array of project names and IRRs
//!         For i = 1 To m_projects.Count
//!             projectData = m_projects(i)
//!             
//!             On Error Resume Next
//!             projectIRR = IRR(projectData(1))
//!             If Err.Number <> 0 Then projectIRR = -999999
//!             On Error GoTo 0
//!             
//!             rankings(i) = Array(projectData(0), projectIRR)
//!         Next i
//!         
//!         ' Sort by IRR (descending)
//!         For i = 1 To UBound(rankings) - 1
//!             For j = i + 1 To UBound(rankings)
//!                 If rankings(j)(1) > rankings(i)(1) Then
//!                     temp = rankings(i)
//!                     rankings(i) = rankings(j)
//!                     rankings(j) = temp
//!                 End If
//!             Next j
//!         Next i
//!         
//!         ' Build result string
//!         result = "Project Rankings:" & vbCrLf
//!         For i = 1 To UBound(rankings)
//!             result = result & i & ". " & rankings(i)(0) & ": " & _
//!                      Format$(rankings(i)(1) * 100, "0.00") & "%" & vbCrLf
//!         Next i
//!         
//!         GetRankedProjects = result
//!     End Function
//! End Class
//!
//! ' Example 3: Capital budgeting calculator
//! Function EvaluateCapitalProject(initialCost As Double, annualSavings As Double, _
//!                                years As Integer, salvageValue As Double, _
//!                                hurdleRate As Double) As String
//!     Dim cashFlows() As Double
//!     Dim i As Integer
//!     Dim projectIRR As Double
//!     Dim result As String
//!     
//!     ReDim cashFlows(0 To years)
//!     cashFlows(0) = -Abs(initialCost)
//!     
//!     For i = 1 To years - 1
//!         cashFlows(i) = annualSavings
//!     Next i
//!     
//!     cashFlows(years) = annualSavings + salvageValue
//!     
//!     projectIRR = IRR(cashFlows)
//!     
//!     result = "Capital Project Evaluation" & vbCrLf
//!     result = result & "Initial Cost: " & Format$(initialCost, "Currency") & vbCrLf
//!     result = result & "Annual Savings: " & Format$(annualSavings, "Currency") & vbCrLf
//!     result = result & "Project Life: " & years & " years" & vbCrLf
//!     result = result & "Salvage Value: " & Format$(salvageValue, "Currency") & vbCrLf
//!     result = result & "IRR: " & Format$(projectIRR * 100, "0.00") & "%" & vbCrLf
//!     result = result & "Hurdle Rate: " & Format$(hurdleRate * 100, "0.00") & "%" & vbCrLf
//!     
//!     If projectIRR >= hurdleRate Then
//!         result = result & "Recommendation: APPROVE"
//!     Else
//!         result = result & "Recommendation: REJECT"
//!     End If
//!     
//!     EvaluateCapitalProject = result
//! End Function
//!
//! ' Example 4: Real estate investment analyzer
//! Function AnalyzeRealEstateInvestment(purchasePrice As Double, downPayment As Double, _
//!                                      monthlyRent As Double, monthlyExpenses As Double, _
//!                                      years As Integer, appreciationRate As Double) As String
//!     Dim cashFlows() As Double
//!     Dim i As Integer
//!     Dim salePrice As Double
//!     Dim annualIRR As Double
//!     Dim result As String
//!     
//!     ReDim cashFlows(0 To years)
//!     
//!     ' Initial investment (down payment)
//!     cashFlows(0) = -Abs(downPayment)
//!     
//!     ' Annual net cash flows
//!     For i = 1 To years - 1
//!         cashFlows(i) = (monthlyRent - monthlyExpenses) * 12
//!     Next i
//!     
//!     ' Final year includes sale
//!     salePrice = purchasePrice * ((1 + appreciationRate) ^ years)
//!     cashFlows(years) = (monthlyRent - monthlyExpenses) * 12 + salePrice - (purchasePrice - downPayment)
//!     
//!     annualIRR = IRR(cashFlows)
//!     
//!     result = "Real Estate Investment Analysis" & vbCrLf
//!     result = result & "Purchase Price: " & Format$(purchasePrice, "Currency") & vbCrLf
//!     result = result & "Down Payment: " & Format$(downPayment, "Currency") & vbCrLf
//!     result = result & "Monthly Rent: " & Format$(monthlyRent, "Currency") & vbCrLf
//!     result = result & "Monthly Expenses: " & Format$(monthlyExpenses, "Currency") & vbCrLf
//!     result = result & "Holding Period: " & years & " years" & vbCrLf
//!     result = result & "Annual IRR: " & Format$(annualIRR * 100, "0.00") & "%"
//!     
//!     AnalyzeRealEstateInvestment = result
//! End Function
//! ```
//!
//! ## Error Handling
//!
//! The IRR function can raise errors:
//!
//! - **Invalid procedure call (Error 5)**: If IRR can't find a result after 20 iterations, or if array doesn't contain at least one positive and one negative value
//! - **Type Mismatch (Error 13)**: If values array is not numeric
//! - **Subscript out of range (Error 9)**: If array is invalid
//!
//! ```vb
//! On Error GoTo ErrorHandler
//! Dim cashFlows(0 To 4) As Double
//! Dim rate As Double
//!
//! cashFlows(0) = -10000
//! cashFlows(1) = 3000
//! cashFlows(2) = 3500
//! cashFlows(3) = 4000
//! cashFlows(4) = 4500
//!
//! rate = IRR(cashFlows)
//! Debug.Print "IRR: " & Format$(rate * 100, "0.00") & "%"
//! Exit Sub
//!
//! ErrorHandler:
//!     If Err.Number = 5 Then
//!         MsgBox "Unable to calculate IRR. Try a different guess value.", vbCritical
//!     Else
//!         MsgBox "Error calculating IRR: " & Err.Description, vbCritical
//!     End If
//! ```
//!
//! ## Performance Considerations
//!
//! - **Iterative Calculation**: `IRR` uses iterative algorithm that can be slow for complex cash flows
//! - **Convergence**: May require multiple iterations; providing good `guess` can improve performance
//! - **Array Size**: Larger arrays take longer to process
//! - **Caching**: Cache calculated `IRR` values rather than recalculating repeatedly
//!
//! ## Best Practices
//!
//! 1. **Validate Input**: Ensure array contains at least one positive and one negative value
//! 2. **Error Handling**: Always wrap `IRR` in error handler as it may fail to converge
//! 3. **Sign Convention**: Use negative for cash outflows (investments), positive for inflows (returns)
//! 4. **Provide Guess**: For complex cash flows or when default fails, provide appropriate guess value
//! 5. **Regular Intervals**: Ensure cash flows occur at regular, consistent intervals
//! 6. **Order Matters**: Values must be in chronological order in the array
//! 7. **Hurdle Rate**: Compare `IRR` to hurdle rate or cost of capital to make decisions
//! 8. **Multiple IRRs**: Be aware that some cash flow patterns can have multiple valid `IRR`s
//! 9. **Complement with NPV**: Use `NPV` alongside `IRR` for complete investment analysis
//! 10. **Format for Display**: Multiply by 100 and format as percentage for user display
//!
//! ## Comparison with Related Functions
//!
//! | Function | Purpose | Return Value | Use Case |
//! |----------|---------|--------------|----------|
//! | `IRR` | Internal rate of return | Rate (`Decimal`) | Evaluate single investment profitability |
//! | `MIRR` | Modified `IRR` | Rate (`Decimal`) | Handle reinvestment assumptions |
//! | `NPV` | Net present value | `Currency` amount | Calculate dollar value at given rate |
//! | `PV` | Present value | `Currency` amount | Simple annuity present value |
//! | `FV` | Future value | `Currency` amount | Simple annuity future value |
//!
//! ## Platform and Version Notes
//!
//! - Available in all VB6 versions
//! - Part of VBA financial functions
//! - Uses `Double` precision
//! - Consistent with Excel's `IRR` function
//! - Maximum 20 iterations for convergence
//!
//! ## Limitations
//!
//! - Assumes cash flows occur at regular intervals
//! - May fail to converge for certain cash flow patterns
//! - Assumes reinvestment at the `IRR` rate (use `MIRR` for different assumption)
//! - Cannot handle irregular time periods between cash flows (use `XIRR` in Excel for that)
//! - Multiple `IRR`s possible for some cash flow patterns (multiple sign changes)
//! - Does not account for risk differences between projects
//!
//! ## Related Functions
//!
//! - `MIRR`: Modified internal rate of return with reinvestment rate
//! - `NPV`: Net present value
//! - `PV`: Present value
//! - `FV`: Future value
//! - `Rate`: Interest rate per period

#[cfg(test)]
mod tests {
    use crate::*;

    #[test]
    fn irr_basic() {
        let source = r"
Sub Test()
    rate = IRR(cashFlows)
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_with_guess() {
        let source = r"
Sub Test()
    rate = IRR(cashFlows, 0.1)
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_array_literal() {
        let source = r"
Sub Test()
    Dim flows(0 To 4) As Double
    rate = IRR(flows)
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_if_statement() {
        let source = r#"
Sub Test()
    If IRR(cashFlows) > 0.15 Then
        MsgBox "Acceptable investment"
    End If
End Sub
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_function_return() {
        let source = r"
Function CalculateReturn() As Double
    CalculateReturn = IRR(projectCashFlows)
End Function
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_comparison() {
        let source = r"
Sub Test()
    If IRR(project1) > IRR(project2) Then
        selectedProject = 1
    End If
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_format() {
        let source = r#"
Sub Test()
    formatted = Format$(IRR(cashFlows) * 100, "0.00") & "%"
End Sub
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_debug_print() {
        let source = r#"
Sub Test()
    Debug.Print "IRR: " & Format$(IRR(cashFlows) * 100, "0.00") & "%"
End Sub
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_variable_assignment() {
        let source = r"
Sub Test()
    Dim returnRate As Double
    returnRate = IRR(investmentFlows)
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_property_assignment() {
        let source = r"
Sub Test()
    investment.ReturnRate = IRR(investment.CashFlows)
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_in_class() {
        let source = r"
Private Sub Class_Initialize()
    m_irr = IRR(m_cashFlows)
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_with_statement() {
        let source = r"
Sub Test()
    With project
        .IRR = IRR(.CashFlows, .Guess)
    End With
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_function_argument() {
        let source = r"
Sub Test()
    Call EvaluateInvestment(IRR(cashFlows))
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_select_case() {
        let source = r#"
Sub Test()
    Select Case IRR(cashFlows)
        Case Is > 0.2
            rating = "Excellent"
        Case Is > 0.1
            rating = "Good"
    End Select
End Sub
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_msgbox() {
        let source = r#"
Sub Test()
    MsgBox "Investment return: " & Format$(IRR(cashFlows) * 100, "0.00") & "%"
End Sub
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_collection_add() {
        let source = r"
Sub Test()
    results.Add IRR(projectFlows(i))
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_math_expression() {
        let source = r"
Sub Test()
    spread = IRR(project1) - IRR(project2)
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_iif() {
        let source = r#"
Sub Test()
    decision = IIf(IRR(cashFlows) > hurdleRate, "Approve", "Reject")
End Sub
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_for_loop() {
        let source = r"
Sub Test()
    Dim i As Integer
    For i = 1 To projectCount
        projectIRRs(i) = IRR(projectFlows(i))
    Next i
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_do_loop() {
        let source = r"
Sub Test()
    Do While IRR(currentFlows) < targetRate
        currentFlows(1) = currentFlows(1) + 1000
    Loop
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_boolean_expression() {
        let source = r"
Sub Test()
    isAcceptable = IRR(cashFlows) > hurdleRate And totalCost < budget
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_error_handling() {
        let source = r"
Sub Test()
    On Error Resume Next
    rate = IRR(cashFlows, 0.2)
    If Err.Number = 0 Then
        Debug.Print rate
    End If
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_multiplication() {
        let source = r"
Sub Test()
    percentageRate = IRR(cashFlows) * 100
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_parentheses() {
        let source = r"
Sub Test()
    value = (IRR(cashFlows))
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_concatenation() {
        let source = r#"
Sub Test()
    result = "IRR: " & IRR(cashFlows)
End Sub
"#;
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_array_access() {
        let source = r"
Sub Test()
    projectRates(index) = IRR(projectCashFlows(index))
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }

    #[test]
    fn irr_nested_call() {
        let source = r"
Sub Test()
    percentage = CStr(IRR(cashFlows) * 100)
End Sub
";
        let (cst_opt, _failures) = ConcreteSyntaxTree::from_text("test.bas", source).unpack();
        let cst = cst_opt.expect("CST should be parsed");

        let tree = cst.to_serializable();

        let mut settings = insta::Settings::clone_current();
        settings
            .set_snapshot_path("../../../../../snapshots/syntax/library/functions/financial/irr");
        settings.set_prepend_module_to_snapshot(false);
        let _guard = settings.bind_to_scope();
        insta::assert_yaml_snapshot!(tree);
    }
}