我有一个VB6 EXE程序,可以从VBA内部传递的字符串中获取子字符串。如何在VBA中捕获extract的值(我对VBA Mid函数不感兴趣)
在VB6中
Private Sub Main()
Extract (command$)
End Sub
Function Extract(StrKey As String)
LastPoss = InStr(StrKey, "_") + 1
Extract = Mid(StrKey, LastPoss, Len(StrKey))
End Function
在VBA中
Sub test()
aaa = "c:\EzPasteImages\Project1.exe "**strong text**
ccc = "ghhfghfgh_hgfhg" 'the parameter
go = aaa & " " & ccc
RET= Shell (go)
End Sub
要解决问题,需要EXE与VBA之间的通信机制。当前,EXE对Extract方法的结果不执行任何操作。为了将结果返回到VBA,请将结果放入StdOut:
Option Explicit
Private Sub Main()
Dim e As String
e = Extract(Command)
Dim fso As FileSystemObject
Set fso = New FileSystemObject
Dim stdOutput As TextStream
Set stdOutput = fso.GetStandardStream(StdOut)
stdOutput.WriteLine e
End Sub
Private Function Extract(ByVal StrKey As String) As String
Extract = Mid(StrKey, InStr(StrKey, "_") + 1, Len(StrKey))
End Function
在VBA上,这是从StdOut获得结果的方法:
Option Explicit
Public Sub Test()
Dim ret As String
ret = ShellRun("c:\TEMP\Extract\Extract.exe" & " " & "ghhfghfgh_hgfhg")
MsgBox ret
End Sub
Public Function ShellRun(sCmd As String) As String
'run a shell command and return stdout as a string
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
Dim oExec As Object
Set oExec = oShell.Exec(sCmd)
Dim s As String
s = oExec.StdOut.ReadAll
ShellRun = Left(s, Len(s) - 2)
End Function
ShellRun
代码来自this link。