This is a pet peeve of mine:
s = s & "Public Sub Init(ByRef hWnd As LongPtr _" & n
I hate large blocks of code with this type of concatenation. I prefer to add each line to a Dictionary and join its keys. But since the text being concatenated is quite large and prewritten, I will spend 5 minutes figuring out how to generate the code.
For this example I dumped some sample code into a module and wrote this function to parse the modules code and copy the result to the clipboard.
Sub PrepareCode()
Dim Lines() As String
With ThisWorkbook.VBProject.VBComponents("APICode").CodeModule
Lines = Split(.Lines(1, .CountOfLines), vbNewLine)
End With
Dim n As Long
For n = 0 To UBound(Lines)
Lines(n) = "Lines(" & n & ") = " & Chr(34) & Replace(Lines(n), Chr(34), String(2, 34)) & Chr(34)
Next
With New DataObject
.SetText Join(Lines, vbNewLine)
.PutInClipboard
End With
End Sub
APICode: Module
#If VBA7 Then
Private Declare PtrSafe Function IsWindow Lib "user32" (ByVal hWnd As LongPtr) As Long
Private Declare PtrSafe Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As LongPtr, ByVal wMsg As Long, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As LongPtr
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#Else
Private Declare Function IsWindow Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If
Output
Lines(0) = "Option Explicit"
Lines(1) = ""
Lines(2) = ""
Lines(3) = "#If VBA7 Then"
Lines(4) = " Private Declare PtrSafe Function IsWindow Lib ""user32"" (ByVal hWnd As LongPtr) As Long"
Lines(5) = " Private Declare PtrSafe Function SendMessage Lib ""user32"" Alias ""SendMessageA"" (ByVal hWnd As LongPtr, ByVal wMsg As Long, ByVal wParam As LongPtr, ByVal lParam As LongPtr) As LongPtr"
Lines(6) = " Public Declare PtrSafe Sub Sleep Lib ""kernel32"" (ByVal dwMilliseconds As Long)"
Lines(7) = "#Else"
Lines(8) = " Private Declare Function IsWindow Lib ""user32"" (ByVal hWnd As Long) As Long"
Lines(9) = " Private Declare Function SendMessage Lib ""user32"" Alias ""SendMessageA"" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long"
Lines(10) = " Public Declare Sub Sleep Lib ""kernel32"" (ByVal dwMilliseconds As Long)"
Lines(11) = "#End If"
Lines(12) = ""
I'm looking forward to testing this code out with a snake game I made a while back!