使用Excel宏

时间:2018-04-04 10:29:06

标签: excel vba excel-vba

我的学校项目有问题 - 所以我现在有一个VBA代码将所有不同的工作簿组合成一个主工作簿。但是,只要个别工作簿发生更改,我就需要刷新和更新主工作簿。有没有我能做到的代码?请帮我!!!我的代码如下:

Sub ConslidateWorkbooks()
'Code to pull sheets from multiple Excel files in one file directory
'into master "Consolidation" sheet.

Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet

Application.ScreenUpdating = False
FolderPath = "C:\Users\gayle_000\Desktop\Bulgari\"       'I have this filled in my code
Filename = Dir(FolderPath & "*.xls*")

Do While Filename <> ""
 Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
 For Each Sheet In ActiveWorkbook.Sheets
 copyOrRefreshSheet ThisWorkbook, Sheet
 Next Sheet
 Workbooks(Filename).Close
 Filename = Dir()
Loop

Application.ScreenUpdating = True

End Sub
Sub copyOrRefreshSheet(destWb As Workbook, sourceWs As Worksheet)
  Dim ws As Worksheet
  On Error Resume Next
  Set ws = destWb.Worksheets(sourceWs.Name)
  On Error GoTo 0
  If ws Is Nothing Then
    sourceWs.Copy After:=destWb.Worksheets(destWb.Worksheets.Count)
  Else
    ws.Cells.ClearContents
    ws.Range(sourceWs.UsedRange.Address).Value = sourceWs.UsedRange.Value2
  End If
End Sub

0 个答案:

没有答案