我想将字符串传递为/ out参数到过程。我知道这不像VBA通常是有效,但这是因为一个特殊的案例。我有一个已经存在的代码生成器工具 - 为文件格式解析器生成代码。而且我不想破解这个代码。生成的语法可以轻松地使用文本转换为VBA替换这没有大不了(我已经完成了这个)。但很难将产品改变为功能。

我想出来是如何通过传递指针来扩展字符串。但是如何将字符附加到字符串?

Option Explicit

Private Declare Sub CopyMemory Lib "kernel32" _
Alias "RtlMoveMemory" (Destination As Any, Source As Any, _
    ByVal length As Long)

Private Declare Function lstrlenA Lib "kernel32" _
   (ByVal lpString As Long) As Long

Private Declare Function lstrlenW Lib _
  "kernel32" (ByVal lpString As Long) As Long


Sub AppendString(i_pt As Long, i_what As String)
    Dim strLentgh As Long                  ' variable to hold the length of string
    Dim ptrLengthField As Long             ' pointer to 4-byte length field

    ' get the length of the string
    ptrLengthField = i_pt - 4              ' length field is 4 bytes behind
    CopyMemory strLentgh, ByVal ptrLengthField, 4

    ' extend the String length
    strLentgh = strLentgh + (Len(i_what) * 2)
    CopyMemory ByVal ptrLengthField, strLentgh&, 4

    ' How to apped the string?
    ' CopyMemory ByVal i_pt, ????
End Sub

Sub test2()
    Dim str As String
    Dim sPtr As Long

    str = "hello"
    sPtr = strPtr(str)

    Debug.Print Len(str)
    Call AppendString(sPtr, " there")
    Debug.Print Len(str)
    Debug.Print str
End Sub
.

有帮助吗?

解决方案

VBA can do this natively

Sub AppendString(byref str as string, i_what As String)
    str = str & i_what
end sub

To test

Sub Test()
    Dim s As String

    s = "Hello"

    AppendString s, " World"
    Debug.Print s
End Sub
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top