首页 > 解决方案 > VBA:将数组中的项目与字符串组合

问题描述

我在将字符串连接在一起时遇到了麻烦。我希望我的输出看起来像

Sub chkstr()
    whoami = ExecShellCmd("whoami")
    arrWhoami = Split(whoami, "\")
    username = arrWhoami(1)

    Debug.Print "C:\folder_one\foler_two\" & username & "_info.txt"
End Sub
results: C:\folder_one\folder_two\myusername_info.txt

但它正在用这样的换行符返回字符串

C:\folder_one\folder_two\myusername
_info.txt

关于我如何让它达到上半部分的结果的任何想法

标签: arraysexcelvbastring

解决方案


我可能在这里走错了路,但我想知道你是否使用了一个看起来像这样的函数:

Public Function ExecShellCmd(FuncExec As String) As String
    Dim wsh As Object, wshOut As Object, sShellOut As String, sShellOutLine As String
    
    'Create object for Shell command execution
    Set wsh = CreateObject("WScript.Shell")

    'Run Excel VBA shell command and get the output string
    Set wshOut = wsh.exec(FuncExec).stdout

    'Read each line of output from the Shell command & Append to Final Output Message
    While Not wshOut.AtEndOfStream
        sShellOutLine = wshOut.ReadLine
        If sShellOutLine <> "" Then
            sShellOut = sShellOut & sShellOutLine & vbCrLf
        End If
    Wend

    'Return the Output of Command Prompt
    ExecShellCmd = sShellOut
End Function

如果是这样,您可以对其进行重构,以便它不会首先放入最后的换行符:

Public Function ExecShellCmd(FuncExec As String) As String
    Dim wsh As Object, wshOut As Object, sShellOut As String, sShellOutLine As String
    
    'Create object for Shell command execution
    Set wsh = CreateObject("WScript.Shell")

    'Run Excel VBA shell command and get the output string
    Set wshOut = wsh.exec(FuncExec).stdout

    'Read each line of output from the Shell command & Append to Final Output Message
    While Not wshOut.AtEndOfStream
    
    ' Put new line in only if there is something more to be read
    
        If sShellOut <> "" Then sShellOut = sShellOut & vbCrLf
        sShellOutLine = wshOut.ReadLine
        Debug.Print (sShellOutLine)
        If sShellOutLine <> "" Then
            sShellOut = sShellOut & sShellOutLine
        End If
    Wend

    'Return the Output of Command Prompt
    ExecShellCmd = sShellOut
End Function

推荐阅读