VBScript更改文件夹中所有文件的Excel宏

时间:2017-03-09 12:30:35

标签: excel vba excel-vba vbscript

我目前的问题与问题VBScript to loop through Excel-files and change macroVBScript to add code to Excel workbook密切相关。所以我想要解决的问题是循环遍历文件夹中的所有Excel文件并更改宏,在某些文件中调用DieseArbeitsmappe和某些ThisWorkbook。以下代码打开每个Excel并保存它但不更改VBComponent。问题必须与返回组件的函数有关,因为我上次发布的代码是我发布的。

这是我的实际代码:

Set objFSO = CreateObject("Scripting.FileSystemObject")
sFolder = "P:\Administration\Reports\operativ\Tagesbericht\templates\START07\TestTabsiNeu\"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False

On Error Resume Next
For Each objFile In objFSO.GetFolder(sFolder).Files

    Set objWorkbook = objExcel.Workbooks.Open(sFolder & objFile.Name)

    Set component = extractedComponent(objWorkbook)

    strCode = _
    "Sub WorkBook_Open()" & vbCr & _
    "   Application.Run (""'CommonMacro.xlsm'!Workbook_Open"")" & vbCr & _
    "End Sub"
    component.CodeModule.AddFromString strCode

    objWorkbook.SaveAs "P:\Administration\Reports\operativ\Tagesbericht\templates\START07\TestTabsiNeu\" & objFile.Name
    objWorkbook.Close
    Set component = Nothing
    Set objWorkbook = Nothing       
Next

objExcel.Quit
Set objFSO = Nothing


Function extractedComponent(objWorkbook)
    Err.Clear
    Set comp = objWorkbook.VBProject.VBComponents("DieseArbeitsmappe")
    If Err.Number = 0 Then
        extractedComponent = comp
        Exit Function
    Else
        Err.Clear
        Set altComp = objWorkbook.VBProject.VBComponents("ThisWorkbook")
        If Err.Number = 0 Then
            extractedComponent = altComp
            Exit Function
        End If
    End If
End Function

1 个答案:

答案 0 :(得分:0)

Set extractedComponent = comp
Set extractedComponent = altComp

要从函数返回对象,您应该Set返回值,以便函数调用理解它正在返回一个对象,&可以正确地将其分配给您的component变量。

我还建议启用错误,以便更好地了解可能失败的内容。