Excel VBA:如何将字符串作为指针传递给附加字符串的过程?

时间:2011-05-18 13:34:35

标签: excel-vba kernel32 vba excel

我想将一个String作为in / out参数传递给一个过程。我知道这不像VBA通常有效,但这是因为一个特例。我有一个已经存在的代码生成器工具 - 为文件格式解析器生成代码。而且我不想破解这段代码。生成的语法可以很容易地转换为vba使用文本替换这没什么大不了的(我已经这样做了)。但很难将功能改为功能。

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

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

1 个答案:

答案 0 :(得分:0)

VBA可以原生地执行此操作

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

测试

Sub Test()
    Dim s As String

    s = "Hello"

    AppendString s, " World"
    Debug.Print s
End Sub