【问题标题】:VBA: combining an item from an array with a stringVBA:将数组中的项目与字符串组合
【发布时间】:2021-10-17 00:11:04
【问题描述】:

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

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

关于我如何使其达到顶部结果的任何想法

【问题讨论】:

  • 然后试试:username = replace(arrWhoami(1),chr(10),"")
  • 你能分享whoami字符串吗?提取的username 应包含结束行字符(vbCr、vbLf 等)。否则,将无法获得您向我们展示的内容。替换讨论中的字符会解决问题,但最好理解为什么这样的字符串,我认为......
  • 由于您只使用用户名部分,也许这将有助于决定如何检索用户名。 stackoverflow.com/questions/39656844/…
  • 为什么不用Environ("username")来获取用户名呢?

标签: arrays excel vba string


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-01-16
    • 1970-01-01
    • 2014-12-22
    • 2018-03-05
    • 2014-09-14
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多