Skip to content

Instantly share code, notes, and snippets.

@n2o
Created March 26, 2025 15:24
Show Gist options
  • Save n2o/2fce8a8e4ac3dff635fa1afafd0638a8 to your computer and use it in GitHub Desktop.
Save n2o/2fce8a8e4ac3dff635fa1afafd0638a8 to your computer and use it in GitHub Desktop.
SHA256-Function in VBA for Mac-Users and Microsoft Excel

SHA256-Function in VBA for Mac-Users and Microsoft Excel

I needed a function to hash a cell's content in Microsoft Excel. Internal calls to .NET functions don't work on a Mac. Also the Python-Integration is only available in Business-Plans. So I wrote a VBA function to hash a string with SHA256 on a Mac.

This VBA function uses the Mac's internal sha256 implementation, makes a system call and returns the hash. The function is called SHA256_Mac and takes a string as input. The function returns the hash as a string.

Add it to your macro-enabled Excel file and use it like this:

=SHA256_Mac("abc")

=> BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD

Or reference a cell:

=SHA256_Mac(A1)

Function SHA256_Mac(text As String) As String
    Dim script As String
    Dim result As String

    'Escape special characters
    Dim safeText As String
    safeText = Replace(text, "'", "'\''")
    safeText = Replace(safeText, """", "\""")

    'Explicit UTF-8 encoding
    script = "do shell script ""export LANG=en_US.UTF-8; printf '%s' '" & safeText & "' | shasum -a 256 | cut -d ' ' -f 1"""

    On Error Resume Next
    result = MacScript(script)
    On Error GoTo 0

    'Clean result
    result = Trim(result)
    If Len(result) = 64 Then
        SHA256_Mac = UCase(result)
    Else
        SHA256_Mac = "ERROR: " & result
    End If
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment