2017-03-09 42 views
0

我目前的問題與問題VBScript to loop through Excel-files and change macroVBScript to add code to Excel workbook密切相關。所以我想解決的問題是遍歷文件夾中的所有Excel文件並更改宏,在一些文件中稱爲DieseArbeitsmappeThisWorkbook。以下代碼打開每個Excel並保存它,但不會更改VBComponent。這個問題必須與返回組件的函數有關,因爲我上次發佈的代碼是張貼的。VBScript更改文件夾中所有文件的Excel宏

這是我的實際代碼:

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 

回答

0
Set extractedComponent = comp 
Set extractedComponent = altComp 

從函數返回的對象,你應該Set婷的返回值使得函數調用理解它返回一個對象,&能將其正確分配給您的變量component

我還建議打開錯誤,以便更好地瞭解可能失敗的內容。

相關問題