Detailed explanation of VBA API

Office version changes

 Before office2010, Microsoft only provided a 32-bit version, but after 2010 there were two versions of office, 32-bit and 64-bit. The latter can handle larger data and the running speed of VBA code is improved. Code compatibility has also become complicated, especially API declarations.
 After Office 2010, there are two versions of office. 64-bit Excel can handle larger data and performance has been improved. With the introduction of 64-bit, a new version of VBA or VBA 7 was also introduced. It can run in two versions at the same time. When installing office2010, the default installation version is 32-bit. If you need a 64-bit version, you need to manually select it.
 In VBA 7, the previous version of the API must be re-declared to run in 64-bit. The address pointer and window handle declaration used in the statement must be updated.

Windows system version

 64-bit offic can refer to a larger memory address space and use more physical memory than before. In addition to referencing the application program for storing data or storing code instructions (pointers), the address can also be used to refer to the displayed window handle. Determine the size of the pointer or handle (in bytes) according to whether the 32-bit or 64-bit system is used.

When running 64-bit Office, you will face two basic problems:

  • The native 64-bit process in the office cannot load 32-bit binary files. When using ActiveX controls and existing plug-ins, they will not be compatible.
  • VBA 7 did not provide pointer data types before. If developers use 32-bit variables to store pointers or handles, part of the value is discarded when using the 64-bit value returned by the API defined by Declare.

VBA7 code changes

 VBA7 is a new code base, it replaces the earlier version of VBA, it is suitable for 32-bit and 64-bit Office. It provides two conditional compilation constants: VBA7 and Win64.

VBA7 constant:
 Determine whether the application uses VBA7 or the previous version of VBA, to ensure the backward compatibility of the code.

Win64 constant:
 Determine whether the code runs in 32-bit or 64-bit form.

ActiveX Control and COM Add-in compatibility

 The existing 32-bit ActiveX controls (including those provided by third parties and Microsoft) are not compatible with the 64-bit version of Office. For ActiveX controls and Com objects, there are three possible solutions:

  • If the source code is available, a 64-bit version can be generated.
  • Contact the supplier for updates.
  • Look for other solutions.

 Native 64-bit processes in Office cannot load 32-bit binary files. Including MSComCtl common controls (TabStrip, Toolbar, StatusBar, ProgressBar, TreeView, ListViews, ImageList, Slider, ImageComboBox) and MSComCt2 controls (Animation, UpDown, MonthView, DateTimePicker, FlatScrollBar), these controls are installed by the previous Office or the current 32-bit office, When migrating to 64-bit Office, the existing controls must be replaced. 64-bit Office does not provide 64-bit universal controls.

Windows API interface compatibility

 The VBA type library provides many functions, but sometimes it is necessary to directly communicate with the computer's operating system and other components, such as when managing memory and processes, or when using the user interface or modifying the registry. In these usage scenarios, the best choice It is the outgoing function of the embedded dynamic link library (DLL). Use Delcare statement to import Dll function in VBA.

The syntax structure of the Delare statement is as follows, to see if there is a return type:

Public/Private Declare Sub SubName Lib "LibName" Alias "AliasName" (argument list)

Public/Private Declare Function FunctionName Lib "Libname" alias "aliasname"(argument list) As Type


 SubName function or FunctionName function replaces the exported function name in the DLL. If you want to call the ASCII or Unicode version of the API, you can specify the alias (AliasName). Lib is followed by the Dll name where the imported function is located. The parameter list must contain the same as the exported function passed to the DLL.
 The following API function opens a subkey in the Windows registry and replaces its value.

Declare Function RegOpenKeyA Lib "advapi32.dll" (ByVal Key As Long, ByVal SubKey As String, NewKey As Long) As Long

 This function is in the Windows API dynamic link library Advapi32.dll, and its function name is RegOpenKeyW. The prototype is defined as follows:

LSTATUS RegOpenKeyW(HKEY    hKey,LPCWSTR lpSubKey,PHKEY   phkResult);

 In C and C++, the API can be compiled for 32 and 64 bits. This is because HKEY is defined as a pointer, which can correctly reflect the memory size of the platform where the compiled code is located.
 In the early VBA version, there is no specific pointer data type, so the Long data type is used, and the Long type is 32-bit. When it is used on a system in 64-bit memory, this situation is interrupted, because 32-bit May be truncated or overwrite other memory addresses. These conditions can lead to unpredictable behavior or system crashes.
 To solve this problem, VBA now includes a real pointer data type LongPtr. This new data type can correctly write API import statements.

Declare PtrSafe Function RegOpenKeyW Lib "advapi32.dll" (ByVal hKey as LongPtr,ByVal lpSubKey as string,Byval phkResult as LongPtr) as Long

 The LongPtr data type and PtrSafe feature can correctly declare API import functions on 32-bit and 64-bit systems. The PtrSafe feature indicates to the VBA compiler that the declaration statement is true for 64-bit Office. Without this feature, the Delcare statement will cause compilation errors in 64-bit systems. Note that the PtrSafe statement is optional in the 32-bit nature of Office. The following table provides some descriptions of functions and data types.

Type Item Description
Modifier PtrSafe Indicates that the API is compatible with 64-bit, which is necessary in 64-bit systems.
Data Type LongPtr It is not a real data type, it is a 4-byte data type (Long) on ​​the 32-bit version, and an 8-byte data type (LongLong) on ​​the 64-bit version. This is the recommended method for declaring pointers and handles after VBA 7. It is only supported in 32-bit and 64-bit VBA7.
Data Type LongLong The 8-byte data type is only available in 64-bit Office.
Conversion Operator CLngPtr Convert the expression to LongPtr type.
Conversion Operator CLngLng Convert the expression to LongLong type.
Function VarPtr Variant type address conversion, returns LongPtr in 64 bits, and Long data type in 32 bits.
Function ObjPtr Object address conversion, returns LongPtr in 64 bits, and Long data type in 32 bits.
Function StrPtr String address address conversion, LongPtr is returned in 64 bits, and Long data type is returned in 32 bits.

 Note: API declaration statements without PtrSafe features are considered incompatible with 64-bit Office.
 In summary, there are two conditional compilation constants: VBA7 and Win64. To ensure backward compatibility with previous versions of Office, you can use VBA7 constants to prevent 64-bit code from being used in earlier versions. For different codes between the 32-bit and 64-bit versions, such as an API, which uses LongLong in the 64-bit version, and uses Long in the 32-bit version, you can use Win64 constants. The following examples use these two constants:

#if Win64 Then
	Declare PtrSafe Function MyTestFunc Lib "DllName"(Byval N as LongLong) as LongLong
#else
	Declare  MyTestFunc Lib "DllName"(Byval N as Long) as Long
#End if

#if VBA7 then
	Declare PtrSafe Sub MessageBeep Lib "User32"(Byval N as Long)
#else
	Declare  Sub MessageBeep Lib "User32"(Byval N as Long)
#end if

 In short, if you are writing 64-bit code and want to be compatible with earlier Office, use VBA7 conditional compilation constants. If you are writing 32-bit Office code, the code works the same as the previous version of Office, without conditional compilation constants. If you want to write compatible 32-bit and 64-bit Office, use Win64 to compile constants.

Use StrPtr, VarPtr, ObjPtr

 Use these functions to return pointers (memory addresses) of string types, variant types, and object types.

Basic knowledge of dynamic link library

  A dynamic-link library (DLL) is a module containing functions and data, which can be used by another module or application.
 DLL defines two functions: export function and internal function. Exported functions can be used by other applications, and internal functions are only used internally.
 Windows API is a set of Dlls, each Dll module exports different functions for external modules.
 Each process that loads Dll maps Dll to its virtual memory address space. After the process loads Dll to its virtual address, the improved process can call Dll's export function.

VBA Declaration API

 First find the API function prototype on Microsoft's official website, and then import the function according to the VBA syntax rules. The following functions:

int MessageBox(
  HWND    hWnd,
  LPCTSTR lpText,
  LPCTSTR lpCaption,
  UINT    uType
);

 API functions are defined in C language format. If it is a pointer type, it is defined as a VBA long integer. If it is a secondary pointer, it is defined as an Any type. After office 2010, LongPtr is defined for compatibility with 32-bit and 64-bit pointer types.
 API functions generally have two versions, ASCII and Unicode. The alias specifies a certain version. It is recommended to use the Unicode version and the API function ending in W.

Office 2010 以后定义方式:
'选择VBA变量和C语言字节一致的变量,如 C的int是4Byte等同于VBA的long。VBA7以后多了一个LongPtr类型,在32位为Long类型在64位为LongLong类型。
#if VBA7 Then

public declare ptrSafe Function MessageBox lib "user32.dll" alias MessageBoxW _
(byval hWnd as LongPtr,byval lpText as string,byval lpCaption as string, byval uType as long) as long

#else

public declare  Function MessageBox lib "user32.dll" alias MessageBoxW _
(byval hWnd as Long,byval lpText as string,byval lpCaption as string, byval uType as long) as long

#end if
'上面定义一个Unicode版本的API,同时能兼容各个版本的Office。

 You can join the group to communicate together: 794568082.

Guess you like

Origin blog.csdn.net/qq_25686631/article/details/111191241