从宏按钮执行批处理文件

时间:2016-11-21 11:22:53

标签: excel-vba macros vba excel

我在特定位置有一个批处理文件。此批处理文件在同一位置重命名图像。我只需要通过excel的宏按钮运行这个批处理文件。 此外,是否可以将PREFIX值键入用户输入。如果有人可以为此提供宏,我将不胜感激。

@echo off
SET COUNT=1
SET PREFIX=40054578_Image
FOR /f "tokens=*" %%G IN ('dir /b *.jpg') DO (call :renum "%%G")
GOTO :eof

:renum
ren %1 %PREFIX%-%count%.jpg
set /a count+=1
GOTO :eof

1 个答案:

答案 0 :(得分:0)

在Excel中,将此代码复制到模块顶部:

Private Declare Function OpenProcess _
    Lib "kernel32" _
    (ByVal dwDesiredAccess As Long, _
     ByVal bInheritHandle As Long, _
     ByVal dwProcessId As Long) As Long

Private Declare Function CloseHandle _
    Lib "kernel32" _
    (ByVal hObject As Long) As Long

Private Declare Function WaitForSingleObject _
    Lib "kernel32" _
    (ByVal hHandle As Long, _
     ByVal dwMilliseconds As Long) As Long

现在复制该代码下面的宏并更改路径以匹配您的bat文件名和目录位置:

Sub runBatch()
    Dim path As String
    path = "C:\Users\yourUserName\Desktop\myBatchFile.bat"  '<-- change this

    'Ask user for prefix
    Dim prefix As String
    prefix = InputBox(Prompt:="Enter Prefix: ", Title:="Prefix", Default:="Enter Prefix Here")

    'Make sure something was entered
    If prefix = vbNullString Or prefix = "Enter Prefix Here" Then Exit Sub

    'Run bat file
    procID = Shell(path & " " & prefix, vbNormalFocus)

    If procID = 0 Then
         'Handle Error, Shell Didn't Work
    Else
         hProcess = OpenProcess(&H100000, True, procID)
         WaitForSingleObject hProcess, -1
         CloseHandle hProcess
    End If
End Sub

此宏提示用户在文本框中输入前缀,然后将值传递给批处理文件。现在通过将前缀设置为%1(意味着传递给批处理文件的第一个参数)来更改批处理文件以使用传递的参数:

SET PREFIX=%1

如果要查看传递到批处理文件的值,请添加ECHO并暂停到批处理文件,以便控制台不会立即解除。

@echo off
ECHO Prefix passed in: %1
pause