Excel VBA中的SUM不适用于1个工作簿

时间:2018-09-13 14:10:26

标签: excel vba excel-vba

我有以下代码来创建来自多个Excel工作簿的佣金支付摘要。

代码按计划工作,除了总和不适用于一个工作簿。

我为sum语句尝试了各种选项,但没有一个可以解决该问题。在工作簿中汇总可以很好地工作。

Sub CommissionsCompile()

Dim d As Variant, dIndex As Long
Dim numFiles As Long, NBFiles As Long
Dim path As String
Dim filename As String
Dim bonus As Double


With Application
    .DisplayAlerts = False
    .ScreenUpdating = False
    .EnableEvents = False
End With

districts = Worksheets("Lookups").Range(district).Value

For Each d In districts
    'The folder containing the files to be recap'd
    myPath = fpath & d

    'Finds the name of the first file of type .* in the current directory
    CurrentFileName = Dir(myPath & "\*")

    'Create a workbook for the recap report
    Set Master = ThisWorkbook

    Do While CurrentFileName <> ""
        Workbooks.Open filename:=myPath & "\" & CurrentFileName, UpdateLinks:=0
        Set sourceBook = Workbooks(CurrentFileName)
        On Error GoTo markFile
        Set sourceData = sourceBook.Worksheets(period)
        On Error GoTo 0

        With sourceData
            .Unprotect "analyst"
            If (.AutoFilterMode And .FilterMode) Or .FilterMode Then
                .ShowAllData
            End If
            .Range("z21:z21").Copy
            bonus = [sum(z22:z23)]
        End With
        currentrow = Workbooks(ThisWorkbook.Name).Worksheets("Commissions").UsedRange.Rows.Count
        With Master.Worksheets("Commissions").Range("E" & currentrow + 1)
            .PasteSpecial Paste:=xlValues
          Master.Worksheets("Commissions").Range("F" & currentrow + 1) = bonus
        End With



        Application.CutCopyMode = False

        endrow = Workbooks(ThisWorkbook.Name).Worksheets("Commissions").UsedRange.Rows.Count

        Master.Worksheets("Commissions").Range("A" & currentrow + 1 & ":A" & endrow).Value = sourceData.Range("C1")
        Master.Worksheets("Commissions").Range("B" & currentrow + 1 & ":B" & endrow).Value = sourceData.Range("C2")
        Master.Worksheets("Commissions").Range("C" & currentrow + 1 & ":C" & endrow).Value = sourceData.Range("C3")
        Master.Worksheets("Commissions").Range("D" & currentrow + 1 & ":D" & endrow).Value = sourceData.Range("C5")


nextItem:
        sourceBook.Close savechanges:=False
        'Calling DIR w/o argument finds the next .xlsx file within the current directory.
        CurrentFileName = Dir()

    Loop
Next d

With Application
    .DisplayAlerts = True
    .ScreenUpdating = True
    .EnableEvents = True
End With

Exit Sub

0 个答案:

没有答案