2013-05-13 231 views
2

試圖讓此32位宏在Office 2010 64位上工作。我試着用PTRSAFE但無法得到它的工作.---新手在這個 感謝32位Excel宏與64位不兼容

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 
+0

我測試你的代碼在64位和它爲我工作。只要確保**命名範圍Computer_Name **存在。 – Santosh 2013-05-13 14:41:23

+3

或者,您可以使用'Environ $(「computername」)'獲取計算機名稱。 – Santosh 2013-05-13 14:44:04

+0

@Invnet什麼部分不起作用?你是否在特定的行上發生錯誤? – JMK 2013-05-13 14:45:44

回答

2

的錯誤信息是非常明確的。您必須使用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 

更重要的是,使用Unicode版本:

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 
+0

謝謝,我得到了一些庫錯誤,但能夠解決它.... – Invnet 2013-05-13 16:26:59