I am trying to create an Excel Function which issues an IP address based on a flag condition. The flag is the presence or absence of a 1.
If a 1 is present then an IP address should be issued.
The function is not taking the flag condition into account and issuing an IP address regardless.
Function GetNextIP_002(text As Variant)
Dim ip As String
Dim ip_addr() As String
Dim ip_next As String
Dim cell As Range
ip = text
ip_addr = Split(ip, ".")
ip_next = Trim(Str(Val(ip_addr(3) + 1)))
If ip_next = 256 Then
ip_next = 0
ip_addr(2) = 1
End If
For Each cell In Range("E5:E30")
If cell.Value = " " Then
GetNextIP_002 = " "
ElseIf cell.Value = "1" Then
GetNextIP_002 = ip_addr(0) & "." & ip_addr(1) & "." & ip_addr(2) & "." & ip_next
End If
Next cell
End Function
You wouldn't want to use a for...next loop in a function like this if you are going to use the function in all of those rows. The problem is in G5, the function will loop through all of E5:E30, and output the final result to G5. Then in G6, it will loop through all of E5:E30 again, and output the final result to G6. And so on. Since the last row in your loop E30 has a 1 flag, then anywhere you use this function will end up reading that E30 1 flag.
I've preserved your code as much as possible and moved some things around to make it a sub instead of a function. This should work as you expected:
Sub GetNextIP_002()
Dim ip As String
Dim ip_addr() As String
Dim ip_next As String
Dim cell As Range
ip = Range("G4")
For Each cell In Range("E5:E30")
If cell.Value = " " Then
cell.Offset(0, 2) = " "
ElseIf cell.Value = "1" Then
ip_addr = Split(ip, ".")
ip_next = Trim(Str(Val(ip_addr(3) + 1)))
If ip_next = 256 Then
ip_next = 0
ip_addr(2) = 1
End If
ip = ip_addr(0) & "." & ip_addr(1) & "." & ip_addr(2) & "." & ip_next
cell.Offset(0, 2) = ip
End If
Next cell
End Sub