Invnet
Invnet

Reputation: 27

32 bit Excel macro not working with 64 bit

Trying to get this 32-bit macro to work on Office 2010 64-bit. I tried using PTrSafe but cannot get it working.---Novice at this Thanks

Option Explicit

Private Declare Function fnGetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long


Public Function GetComputerName()
Dim strComputerName As String
Dim lngPos As Long
Const MAX_COMPUTERNAME_LENGTH = 100
Application.ScreenUpdating = False

    strComputerName = String(MAX_COMPUTERNAME_LENGTH + 1, " ")

    If fnGetComputerName(strComputerName, MAX_COMPUTERNAME_LENGTH) = 0 Then
        strComputerName = "ErrorGettingComputerName"
    Else
        lngPos = InStr(1, strComputerName, Chr(0))
        strComputerName = Left(strComputerName, lngPos - 1)
    End If

GetComputerName = strComputerName

    Application.Range("Computer_Name") = GetComputerName

Application.ScreenUpdating = True
End Function

Upvotes: 2

Views: 22737

Answers (1)

GSerg
GSerg

Reputation: 78134

The error message is very clear. You must use PtrSafe:

Option Explicit

#If VBA7 Then
Private Declare PtrSafe Function fnGetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#Else
Private Declare Function fnGetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If

Public Function GetComputerName() As String
    Const MAX_COMPUTERNAME_LENGTH As Long = 31

    Dim buf As String, buf_len As Long

    buf = String$(MAX_COMPUTERNAME_LENGTH + 1, 0)
    buf_len = Len(buf)

    If (fnGetComputerName(buf, buf_len)) = 0 Then
        GetComputerName = "ErrorGettingComputerName"
    Else
        GetComputerName = Left$(buf, buf_len)
    End If
End Function

Better yet, use the Unicode version:

Option Explicit

#If VBA7 Then
Private Declare PtrSafe Function fnGetComputerName Lib "kernel32" Alias "GetComputerNameW" (ByVal lpBuffer As LongPtr, ByRef nSize As Long) As Long
#Else
Private Declare Function fnGetComputerName Lib "kernel32" Alias "GetComputerNameW" (ByVal lpBuffer As Long, ByRef nSize As Long) As Long
#End If

Public Function GetComputerName() As String
    Const MAX_COMPUTERNAME_LENGTH As Long = 31

    Dim buf As String, buf_len As Long

    buf = String$(MAX_COMPUTERNAME_LENGTH + 1, 0)
    buf_len = Len(buf)

    If (fnGetComputerName(StrPtr(buf), buf_len)) = 0 Then
        GetComputerName = "ErrorGettingComputerName"
    Else
        GetComputerName = Left$(buf, buf_len)
    End If
End Function

Upvotes: 3

Related Questions