将数值从PowerShell发送到VBA

时间:2016-10-13 16:53:28

标签: excel-vba powershell vba excel

我想通过PowerShell脚本将一些数值输入到Excel工作表中。我已经可以获得值,但它以字符串形式到达电子表格,不知何故Excel不允许我将其转换为数字。 我希望我只是错过了一步,这并非不可能。

这是VBA部分

strCommand = (PsCommand)
Set wshshell = CreateObject("WScript.Shell")
Set WshShellexec = wshshell.Exec(strCommand)
stroutput = WshShellexec.StdOut.ReadAll
Sheets("Sheet1").Cells(i, 2).Value = stroutput
Sheets("Sheet1").Cells(i, 2).NumberFormat = "0"

我的猜测是这就是问题所在:

Set WshShellexec = wshshell.Exec(strCommand)

1 个答案:

答案 0 :(得分:0)

ReadAll总是返回一个字符串。要将数字字符串转换为整数,请使用scalarificationCInt

Sheets("Sheet1").Cells(i, 2).Value = CLng(stroutput)

请注意,字符串必须只包含一个数字(前导和尾随空格是可以的)。字符串中的其他字符将导致错误。在这种情况下,您需要先将字符串解析出字符串,然后再将其转换为整数。