VBA Add "-" every two characters to form MAC Address

Asked

Viewed 81 times

1

I would like to form a MAC address from the data collected from a barcode reader. I need every two characters to be added one "-".

Entry text: A9B8C7D6E5F4

Output text: A9-B8-C7-D6-E5-F4

So far I have reached the next point of attempted resolution:

Function MACADddress(macaddress As String) As String
    Dim i As Integer

    Dim C As Integer
    Set C = 0

    Dim k As Integer
    Set k = macaddress.lenght

    Dim NewMac As String
    Set NewMac = ""

    For i = 0 To k
        C = C + 1

        If C = 2 Then
            NewMac = NewMac & macaddress(i) & "-"
            C = 0
        Else
           NewMac = NewMac & macaddress(i)
        End If

        MsgBox (NewMac)
    Next i

    MACADddress = NewMac
End Function

1 answer

2


Code

Function MACADddress(macaddress As String) As String
    Dim i As Long, C As Long, k As Long
    Dim NewMac As String
    NewMac = ""
    C = 0
    k = Len(macaddress)

    For i = 1 To k
        C = C + 1
        If C = 2 And i <> k Then
            NewMac = NewMac & Mid(macaddress, i, 1) & "-"
            C = 0
        Else
            NewMac = NewMac & Mid(macaddress, i, 1)
        End If
        'MsgBox (NewMac)
    Next i
    MACADddress = Trim(NewMac)
End Function

Remarks

The function you tried to do is for vectors and matrices and not string.

For strings use the function Len() to get the string size and loop to iterate over each letter of this string.

Then his logic was correct, only the condition was added And i <> k, 'cause I was adding "-" after the last character.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.