对文件夹中存在的数据使用sum函数

时间:2014-02-26 18:55:15

标签: vba excel-vba excel

我正在尝试开发一个代码,以便从特定工作表中为特定文件夹中存在的文件中的值求和。虽然使用了sum函数,但由于usm函数未定义,因此出现了错误。请帮助我是宏的新手。

       Private Sub CommandButton1_Click()
          Const FOLDER As String = "C:\SBI_Files\"
          Const cStrWSName As String = "External Rated Advances"
          Const sourceName As String = "External Credit Rating"
          On Error GoTo ErrorHandler

          Dim i As Integer
           Dim fileName As String



    ThisWorkbook.Worksheets(cStrWSName).Range("C4:H9").ClearContents



     ' P = 4
      j = 1
      fileName = Dir(FOLDER, vbDirectory)
       Do While Len(fileName) > 0

        If Right$(fileName, 4) = "xlsx" Or Right$(fileName, 3) = "xls" Then
        i = i + 1
        Dim currentWkbk As Excel.Workbook
        Set currentWkbk = Excel.Workbooks.Open(FOLDER & fileName)


        'Entity wise consolidation'

        ThisWorkbook.Worksheets(cStrWSName).Cells(3, j + 2).Value = Left(currentWkbk.Name, Len(currentWkbk.Name) - 4)
        ThisWorkbook.Worksheets(cStrWSName).Cells(3, j + 2).Font.Bold = True
       'Out.println (currentWkbk.Sheets(sourceName).Cells(24, 2).Value)
      ' Out.println (currentWkbk.Sheets(sourceName).Cells(27, 3).Value)
      'If currentWkbk.Sheets(sourceName).Cells(27, 3).Value <> 0 Then

        ThisWorkbook.Worksheets(cStrWSName).Cells(4, j + 2).Value = _
          Sum(currentWkbk.Sheets(sourceName).Cells("B8:B23").Value)
 '**** (I got an Sum function not defined error here) ****

        ThisWorkbook.Worksheets(cStrWSName).Cells(5, j + 2).Value = _
          Sum(currentWkbk.Sheets(sourceName).Cells("A8:A23").Value)

        ThisWorkbook.Worksheets(cStrWSName).Cells(6, j + 2).Value = _
           Sum(currentWkbk.Sheets(sourceName).Cells("D8:D23").Value)

         ThisWorkbook.Worksheets(cStrWSName).Cells(7, j + 2).Value = _
           Sum(currentWkbk.Sheets(sourceName).Cells("C8:C23").Value)

      'End If
        j = j + 1
        currentWkbk.Close
        End If
        fileName = Dir
    Loop
    'Rated_Advances_Total_Advance
    ProgramExit:
    Exit Sub
    ErrorHandler:
    MsgBox Err.Number & " - " & Err.Description
    Resume ProgramExit
    End Sub

1 个答案:

答案 0 :(得分:1)

使用工作表中的Excel公式时,请使用以下语法:

Worksheetfunction.Sum

这适用于所有“工作表”的公式。