Excel VBA: ¿Cómo pasar una cadena como puntero a un procedimiento para agregar la cadena?

StackOverflow https://stackoverflow.com/questions/6045592

  •  15-11-2019
  •  | 
  •  

Pregunta

Quiero pasar una cadena como parámetro IN / OUT a un procedimiento.Sé que esto no es como la VBA generalmente funciona, pero esto se debe a un caso especial.Tengo un código generador de herramientas de generador de código ya existente para un analizador de formato de archivo.Y no quiero hackear este código.La sintaxis generada puede ser fácil de convertir a VBA con texto, reemplaza esto, no hay gran problema (ya lo he hecho esto).Pero es difícil cambiar los productos a las funciones.

Lo que he descubierto es cómo puedo extender una cadena pasando su puntero.Pero, ¿cómo puedo agregar los caracteres a la cadena?

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

¿Fue útil?

Solución

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top