For the following code,
If Sheets(\"sheet1\").Range(\"A1\").Value = \"option_1\" Then
Sheets(\"sheet1\").Range(\"A1\").Value = \"option_2\"
ElseIf Sheets
A bit too late, but in the specific example the fastest should be to store the option as a number and just increment it when needed. The Custom Number Format of the cell can be changed to "option_"0;;;
for the number to show as option_#.
In almost all cases I expect the Select Case
to be a just a tiny bit slower and to be compiled to something very similar to If Else statements.
That is not the case in the two examples because they do slightly different things. In the first example, each of the If statements will look for Sheet "sheet1" and get the value of Range "A1", but the Select Case
example gets that value only once in the beginning and then compares that value. This should cause the Select Case
example to be few times faster when the cell value is not "option_1".
Rather than having to type in all the possibilities why not do it like this. (Assuming that the next item is always 1 plus the last item)
Public Sub Test()
With ThisWorkbook.Worksheets("Sheet1").Range("A1")
.Value = "option_" & Val(Mid(.Value, InStrRev(.Value, "_") + 1)) + 1
End With
End Sub
This is more reliable, efficient and will go to infinity, without the infinite lines of code to do it.
For just a few items, it doesn't matter. For larger arrays, use switch. More of the technical details here.
I ran multiple scenarios comparing the "IF" statement with the "Case" statement using a simple "for loop" and "mod" function. The scenarios vary in the number of records checked and the number of conditions (# of ifElse/# of cases). The table below shows the scenarios and the results for each scenario. Note that the speed mentioned in the table is the average of 100 runs.
We can see that the "IF" statement and "Case" statement are almost similar in performance. The "IF" statement slightly beats the "Case" statement (~5% faster).
Excel Version: Office 365 version 1908 build 11929.20300
Processor Used: Intel i9-9900K
As Bazinga says, for just a few items, it doesn't matter. Anyway, you should do add With...end With statements in this case:
With Sheets("sheet1").Range("A1")
If .Value = "option_1" Then
.Value = "option_2"
ElseIf .Value = "option_2" Then
.Value = "option_3"
ElseIf .Value = "option_3" Then
.Value = "option_4"
...
End If
End With
This should be faster and more readable.