Saturday, May 14, 2022

Generating GUID in excel using macro

For some reason, you may need to generate GUID in an excel document. For me, because of using GUID as primary keys in database, I have needed to generate insert scripts and GUIDs as primary keys. First of all you need to activate developer options of excel. After that, you are able to write macros. Finally, create a module and create function given below:

Function createguid()
Dim guid As String
guid = CreateObject("WScript.Shell").Exec("powershell -command [guid]::newGuid().ToString()").StdOut.ReadAll
createguid = Application.WorksheetFunction.Clean(guid)
End Function
In this approach, powershell is used for GUID generation. You can use this function in formulas after creation. Only drawback of this method is powershell console is opened and closed as many as generated GUIDs.