Results 1 to 2 of 2

Thread: Creating and using Symlinks in VBA?

  1. #1

    Creating and using Symlinks in VBA?

    Has anyone had any success working with Symlinks in VBA code? I've figured out how to create them, but that's about it. Now I need to be able to find out what a symlink points to and that's eluded me. I've searched just about everything with no luck. Anyone know how to do that? I've found a Windows API (GetFinalPathNameByHandle) that supposedly does that, but I can't get it to work.

    I found this code in another forum, but it always fails on "CreateFile" when the path is to a symlink. I am "running as administrator" and my same program will create a symlink ok, so I don't think it's a privilege problem.
    Public Function GetFileFinalPath(ByVal FilePath As String) As String    
        Dim hFile As LongPtr
        Dim FinalPath As String
        Dim PathLength As Long
        ' Open the file handle
        hFile = CreateFile(StrPtr(FilePath), GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)
        If hFile = -1 Then
            GetFileFinalPath = "Error: Unable to open file handle."
            Exit Function
        End If
        ' Prepare buffer for the final path
        FinalPath = String$(260, vbNullChar) ' MAX_PATH is 260
        PathLength = GetFinalPathNameByHandle(hFile, FinalPath, Len(FinalPath), FILE_NAME_NORMALIZED)
        ' Close the file handle
        CloseHandle hFile
        ' Check if the function succeeded
        If PathLength > 0 Then
            GetFileFinalPath = Left$(FinalPath, PathLength)
        Else
            GetFileFinalPath = "Error: Unable to retrieve final path."
        End If
    End Function
    Last edited by Aussiebear; 06-26-2025 at 11:07 AM.

  2. #2
    Chatgpt has some answer:
    ' from Chatgpt
    Sub CreateSymlink(ByVal Target As String, ByVal Link As String)
        Dim cmd As String
        ' Ensure paths are wrapped in quotes
        ' cmd = "cmd /c mklink /D """ & Link & """ """ & Target & """"
        cmd = "cmd /c mklink """ & Link & """ """ & Target & """"
        ' Create the symbolic link
        Shell cmd, vbHide   'vbNormalFocus
    End Sub
    example (will create test.lnk of Document folder)
    Private Sub test()
        Dim path As String
        path = Environ("userprofile") & "\documents\"
        Call CreateSymlink(path & "fileNameHere.xlsx", path & "test.lnk")
    End Sub
    Last edited by Aussiebear; 06-26-2025 at 11:08 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •