Excel VBA:如何将字符串作为指针传递给过程以附加字符串?
我想将字符串作为输入/输出参数传递给过程。我知道这不像 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
I want to pass a String as in/out parameter to a procedure. I know this is not like VBA usually works but this is because of a special case. I have an already existing code generator tool - generating code for a file-format parser. And I do not want to hack this code. The generated syntax can be easily convertet to vba using text replace this no big deal (I have done this already). But It is difficult to change prodedures to functions.
What I have figured out is how I can extend a String by passing its pointer. But How can I append the characters to the 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
VBA 可以本地执行此操作
来测试
VBA can do this natively
To test