vba 32 位 Excel 宏不适用于 64 位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16524705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:05:03 来源:igfitidea点击:
32 bit Excel macro not working with 64 bit
提问by Invnet
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
试图让这个 32 位宏在 Office 2010 64 位上工作。我尝试使用 PTrSafe,但无法使其正常工作。---新手谢谢
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
回答by GSerg
The error message is very clear. You must use PtrSafe
:
错误信息非常清楚。您必须使用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:
更好的是,使用 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