如何在 Excel VBA 中将字符串格式化为 UUID?

How do I format a string to UUID in Excel VBA?

我有一个小 VBA 项目,但遇到了问题。

我需要将一个32个字符的十六进制字符串转成一个UUID。

Input: b10a8db164e0754105b7a99be72e3fe5
Output: b10a8db1-64e0-7541-05b7-a99be72e3fe5

我不知道从哪里开始,但我想我需要在这么多字符之后拆分字符串,然后重新组合它。任何指示或方法可以有效地做到这一点?

您可以使用 LeftRightMid 将其制作成您想要的格式。

Function makeUuid(asString As String) As String
    Dim asUuidFormat As String
    If Len(asString) <> 32 Then
        makeUuid = asString
        Exit Function
    End If
    Dim firstPart As String, secondPart As String, thirdPart As String, fourthPart As String, fifthPart As String
    firstPart = Left(asString, 8)
    secondPart = Mid(asString, 9, 4)
    thirdPart = Mid(asString, 13, 4)
    fourthPart = Mid(asString, 17, 4)
    fifthPart = Right(asString, 12)
    makeUuid = firstPart & "-" & secondPart & "-" & thirdPart & "-" & fourthPart & "-" & fifthPart
End Function

您可以在工作表中将其用作“=makeUuid(A4)”(或任何单元格)

如果您传入的不是 32 位长度的字符串,它不会进行格式化,只是 returns 原始字符串。

A1 中的数据在另一个单元格中:

=MID(A1,1,8) & "-" & MID(A1,9,4) & "-" & MID(A1,13,4) & "-" & MID(A1,17,4) & "-" & MID(A1,21,9999)