我有一个vba宏来取消合并合并的单元格并在excel中重复,但我需要在不打开excel的情况下运行此宏,并且同样的逻辑将应用于多个excel,所以我需要一个批处理文件调用vba并应用于文件夹中的excel。有没有办法做到这一点。
答案 0 :(得分:0)
您可以从批处理文件(循环中)调用此VBscript
<强>用法:强>
CScript inject.vbs“C:\ johan \ VbaStuff \ Empty workbook.xlsx”“C: \ johan \ VbaStuff \ DummyMacro.bas“”AddDateToA1“
<强> inject.vbs:强>
dim oArgs, i, FSO
dim fileName, macroFileName, functionName
dim oApplication, oWorkbooks, oWorkbook, oVbProject
dim oComponents, oModule, fullFunction
Set oArgs = WScript.Arguments
For i = 0 to oArgs.Count - 1
WScript.Echo "Arg" & i & ": " & oArgs(i)
Next
WScript.Echo ""
if oArgs.Count < 3 then
WScript.Echo "Too few arguments"
WScript.Quit
end if
fileName = oArgs(0)
macroFileName = oArgs(1)
functionName = oArgs(2)
set FSO = CreateObject("Scripting.FileSystemObject")
if not FSO.FileExists(fileName) then
WScript.Echo "Excel file does not exist"
WScript.Quit
end if
if not FSO.FileExists(macroFileName) then
WScript.Echo "Macro file does not exist"
WScript.Quit
end if
set oApplication = CreateObject("Excel.Application")
oApplication.DisplayAlerts = False
WScript.Echo "Injecting in Excel version: " & oApplication.Version
set oWorkbooks = oApplication.Workbooks
set oWorkbook = oWorkbooks.Open(fileName)
WScript.Echo oWorkbook.Name
set oVbProject = oWorkbook.VBProject
WScript.Echo oVbProject.Name
set oComponents = oVbProject.VBComponents
set oModule = oComponents.Import(macroFileName)
fullFunction = Trim(oModule.Name & "." & functionName)
WScript.Echo "Full function: '" & fullFunction & "'"
oApplication.Run(fullFunction)
oComponents.Remove(oModule)
oWorkbook.Save()
WScript.Echo "Saved changes"
oWorkbook.Close(False)
Call oApplication.Quit()
set oModule = Nothing
set oComponents = Nothing
set oVbProject = Nothing
set oWorkbook = Nothing
set oWorkbooks = Nothing
set oApplication = Nothing
set FSO = Nothing
虚拟宏的完整性:
Attribute VB_Name = "DummyMacro"
Sub AddDateToA1()
Dim oCell As Range
Dim sTime As String
Set oCell = ThisWorkbook.Sheets(1).Cells(1, 1)
sTime = CStr(TimeValue(Now))
oCell.Value = sTime
MsgBox "Wrote time " & sTime & " to " & oCell.Address(0, 0, xlA1, 1)
End Sub