You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Excel VBA中执行PowerShell修改文件时间时遇语法错误求助

解决VBA调用PowerShell修改文件最后修改时间的语法错误

你的问题出在两个核心语法错误上,导致PowerShell解析命令时出现括号不匹配和引号混乱的问题:

错误原因分析

  1. 括号不匹配:你构造的命令中,Get-Item的调用缺少闭合括号。原本正确的PowerShell命令是(Get-Item "文件路径").LastWriteTime = "时间",但你写的(get-item C:\Users\ron\NWFundPositions.csv没有在路径后加),直接接.lastwritetime,导致PowerShell无法正确识别表达式结构,触发"Missing closing parenthesis ')' in expression"错误。

  2. VBA引号转义错误:在VBA字符串中,要表示一个双引号,必须用两个连续的双引号""来转义,而不是反引号``。你用反引号转义的方式只适用于PowerShell内部,在VBA中会被当作普通字符传递给PowerShell,导致引号配对混乱,进一步加重语法错误。

正确的VBA代码实现

下面是修正后的代码,同时推荐显式使用-Command参数明确指定PowerShell要执行的命令,避免解析歧义:

Sub UpdateFileLastWriteTime()
    Dim strCommand As String
    Dim WshShell As Object
    Dim WshShellExec As Object
    
    ' 构造正确的命令:用单引号包裹路径和时间,避免VBA中转义双引号的繁琐
    strCommand = "powershell -Command ""(Get-Item 'C:\Users\ron\NWFundPositions.csv').LastWriteTime = '16 Jun 2023 18:00:00'"""
    
    Set WshShell = CreateObject("WScript.Shell")
    Set WshShellExec = WshShell.Exec(strCommand)
    
    ' 可选:输出执行结果用于调试
    Debug.Print "标准输出: " & WshShellExec.StdOut.ReadAll()
    Debug.Print "错误输出: " & WshShellExec.StdErr.ReadAll()
    
    ' 释放对象
    Set WshShellExec = Nothing
    Set WshShell = Nothing
End Sub

如果你偏好使用双引号包裹路径和时间,需要在VBA中对双引号进行转义(用""替代"),对应的命令如下:

strCommand = "powershell -Command ""(Get-Item """"C:\Users\ron\NWFundPositions.csv"""").LastWriteTime = """"16 Jun 2023 18:00:00"""""""

内容的提问来源于stack exchange,提问作者Ron Rosenfeld

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 02:52:28