【问题标题】:VBA and PowerShell integration?VBA 和 PowerShell 集成?
【发布时间】:2016-05-30 22:36:37
【问题描述】:

我正在尝试创建一个宏,当数据输入到单元格区域时,它将触发 PowerShell 脚本。在这个 PowerShell 脚本中,我试图从我的 PowerShell 查询中获取对象以返回到触发宏的活动工作表。唯一困难的部分是,工作簿位于 SharePoint 服务器上。

有没有人对如何实现我的目标有任何见解,或者有任何链接可以帮助我指明正确的方向。

谢谢。

【问题讨论】:

    标签: vba excel powershell


    【解决方案1】:

    您将需要一个更改事件,以便您可以在单元格中的数据发生更改时进行检查。

    其次,您需要一个从 powershell 命令返回数据的方法。我只是使用命令行操作中的 >> 运算符将数据放入文本文件中,然后再读取该文本文件。

    第三,您需要对这些数据进行处理。

    Private Sub Worksheet_Change(ByVal Target As Range)
        If Target.Address = "$A$1" Then ' If A1 changes...
        Dim FileNum As Integer
        Dim FileName As String
        Dim DataLine As String
        Dim objShell
        Dim fso
        Set fso = CreateObject("Scripting.FileSystemObject")
        Set objShell = CreateObject("WScript.Shell")
        FileName = "C:\data.txt"
        cmdString = "Powershell DIR >>" + FileName ' Cmd String for Powershell
        Call objShell.Run(cmdString, 0, True) ' Run the command, data is exported to FileName path
    
        FileNum = FreeFile()
        Open FileName For Input As #FileNum ' Open the File we generated
        While Not EOF(FileNum)
            Line Input #FileNum, DataLine ' read in data 1 line at a time
            ' Do something with data line that was saved from the shell script.
        Wend
        Close #FileNum
        Call fso.DeleteFile(FileName) ' Delete the file we generated
        End If
    
    End Sub
    

    【讨论】:

    • 太完美了!非常感谢你,我真的很感激你的洞察力。
    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 2018-02-14
    • 2018-11-20
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多