Excel宏帮助 - 堆叠宏

时间:2010-12-14 06:40:24

标签: excel vba excel-2003

我正在使用以下子例程将单个文件夹中的多个Excel文件合并到一个包含多个工作表的工作簿中。

Sub Merge2MultiSheets()

Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String

Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
MyPath = "C:\MyPath" ' <-- Insert Absolute Folder Location
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFilename = Dir(MyPath & "\*.xls", vbNormal)

If Len(strFilename) = 0 Then Exit Sub

Do Until strFilename = ""            
    Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)                
    Set wsSrc = wbSrc.Worksheets(1)                
    wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)                
    wbSrc.Close False            
    strFilename = Dir()            
Loop
wbDst.Worksheets(1).Delete

Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub

最终产品是包含多个工作表的excel文件(以及一个空白工作表1)。我想知道如何将另一个宏应用于这个新创建的工作簿。作为一个例子,我希望这个新工作簿中的所有工作表都能使它们的Headers变为粗体并以某种方式着色,并删除空的工作表。

例如:

Sub Headers()

Rows("1:1").Select
Selection.Font.Bold = True
With Selection.Interior
    .ColorIndex = 37
    .Pattern = xlSolid
End With
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With

End Sub

3 个答案:

答案 0 :(得分:1)

Sheets.Select       'selects all sheets'
Rows("1:1").Select
Selection.Interior.ColorIndex = 37

答案 1 :(得分:0)

将参数添加到指定工作表的Headers,然后在复制后调用Do循环中的sub,如:

Call Headers(wbDst.Worksheets(wbDst.Worksheets.Count))

你的第二个子看起来像这样:

Sub Headers(workingSheet As Worksheet)

workingSheet.Rows("1:1").Select
Selection.Font.Bold = True
With Selection.Interior
.
.
.

答案 2 :(得分:0)

此代码将执行以下操作:

1)首先,按照您在帖子中的要求删除Sheet1

2)格式化剩余工作表中的第一行

Sub Headers()
Dim wkSheet As Worksheet

//Delete Sheet1. Note that alerts are turned off otherwise you are prompted with a dialog box to check you want to delete sheet1
Application.DisplayAlerts = False
Worksheets("Sheet1").Delete
Application.DisplayAlerts = False

//Loop through each worksheet in workbook sheet collection
For Each wkSheet In ActiveWorkbook.Worksheets
    With wkSheet.Rows("1:1")
        .Interior.ColorIndex = 37
        //Add additional formatting requirements here
    End With
Next

End Sub