I need a function to add a GUID to cells in excel. I found this previous question on stackoverflow, but it is not working. It suggests the following function:
=CO
After trying a number of options and running into various issue with newer versions of Excel (2016) I came across this post from MS that worked like a charm. I enhanced it bit using some code from a post by danwagner.co
Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (Guid As GUID_TYPE) As LongPtr
Private Declare PtrSafe Function StringFromGUID2 Lib "ole32.dll" (Guid As GUID_TYPE, ByVal lpStrGuid As LongPtr, ByVal cbMax As Long) As LongPtr
Function CreateGuidString(Optional IncludeHyphens As Boolean = True, Optional IncludeBraces As Boolean = False)
Dim Guid As GUID_TYPE
Dim strGuid As String
Dim retValue As LongPtr
Const guidLength As Long = 39 'registry GUID format with null terminator {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
retValue = CoCreateGuid(Guid)
If retValue = 0 Then
strGuid = String$(guidLength, vbNullChar)
retValue = StringFromGUID2(Guid, StrPtr(strGuid), guidLength)
If retValue = guidLength Then
' valid GUID as a string
' remove them from the GUID
If Not IncludeHyphens Then
strGuid = Replace(strGuid, "-", vbNullString, Compare:=vbTextCompare)
End If
' If IncludeBraces is switched from the default False to True,
' leave those curly braces be!
If Not IncludeBraces Then
strGuid = Replace(strGuid, "{", vbNullString, Compare:=vbTextCompare)
strGuid = Replace(strGuid, "}", vbNullString, Compare:=vbTextCompare)
End If
CreateGuidString = strGuid
End If
End If
End Function
Public Sub TestCreateGUID()
Dim Guid As String
Guid = CreateGuidString() '<~ default
Debug.Print Guid
End Sub
There are additional options in the original MS post found here: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_excel-msoffice_custom-mso_2010/guid-run-time-error-70-permission-denied/c9ee4076-98af-4032-bc87-40ad7aa7cb38