问题
I am trying to create a macro, that would be able to rename all files with ".docx" extension in a folder.
The PowerShell command works when used directly, but when used through the VBA code, it's not executing.
Sub test()
Dim retval
Dim pscmd
pscmd = "PowerShell -ExecutionPolicy Bypass -Command ""Get-ChildItem -Path *.docx -Recurse | Rename-Item -NewName {$_.Name.Substring(0,7) + $_.Extension }"""
retval = Shell(pscmd, vbNormalFocus)
Debug.Print pscmd
End Sub
The script is executing without compilation errors, but the files are not being renamed.
What do I need to change?
回答1:
You have to provide the path where your files exist Try this and change the path to suit you
Sub Test()
Dim retval, pscmd
pscmd = "PowerShell -ExecutionPolicy Bypass -Command ""Get-ChildItem -Path " & ThisWorkbook.Path & "\Files\" & " *.docx -Recurse | Rename-Item -NewName {$_.Name.Substring(0,7) + $_.Extension }"""
retval = Shell(pscmd, vbNormalFocus)
Debug.Print pscmd
End Sub
来源:https://stackoverflow.com/questions/52956136/vba-macro-to-run-powershell-command