Excel VBA SUM返回零或错误

时间:2017-03-18 15:04:27

标签: excel vba excel-vba

我试图通过关注与Excel.WorksheetFunction.Sum相关的一个问题来简化先前的帖子。我显然不知道如何使用这个函数,因为我一直为结果或抛出错误而得零。

我根本无法让这个工作,我已经工作了三天(字面意思)并且已经完成了近百个不同的测试。虽然我很了解Access VBA,但我是自学成才的,我想我错过了一些关键概念,这就是在Excel中杀了我。

下面的代码来自我所做的测试/调试,文档解释了每个不同版本的结果。子调用函数(问题出在哪里)。

几点:

  1. 当我手动使用Excel时,我可以在工作表上获得SUM。

    1a上。所需范围中的数字并不总是连续的,但如果我将范围缩小到只是连续的数字 - 它仍然不起作用。

  2. 我在Access模块​​中写这个,因为它是Access App的一部分(试图从电子表格中自动导入数据)。

  3. 有人暗示我之前的工作并非“完全合格”,所以我使用With Bloc建立了这个。但是,我可能没有正确地做到这一点。

  4. 任何指导都会非常感激 - 特别是,如果你能够仁慈地解释我在这里缺少的概念。

    Public Function fnImportFileProcessFilePrep2(intClientId As Integer, intEventId As Long, strExcelFileName As String, _
    strActiveSheet As String, strQASumColumn As String)
    On Error GoTo HandleError
    
    Dim intLastCol As Long
    Dim intLastRow As Long
    Dim intNextCol As Long
    Dim intRecordCount As Long
    
    Dim varSumExcelColumns As Variant
    Dim strSUMRange As String
    Dim strAddColumnLabel As String
    Dim dblSum As Double
    
    Dim rgUseRange As Range
    Dim rgSUMRange As Range
    
    Dim strFileName As String
    
    Dim oXLApp As Excel.Application       'Declare the object variables
    Dim oXLBook As Excel.Workbook
    Dim oXLSheet As Excel.Worksheet
    
    Set oXLApp = New Excel.Application      'Create a new instance of Excel
    Set oXLBook = oXLApp.Workbooks.Open(strExcelFileName) 'Open the existing workbook
    Set oXLSheet = oXLBook.Worksheets(strActiveSheet)  'Work with the input worksheet
    
    
      oXLSheet.Activate                   'Activate the Worksheet
      oXLApp.Visible = True               'Show it to the user
      oXLApp.UserControl = True
    
    
        With oXLSheet
            ' Replace ALL "(null)" cells - THIS WORKS!!!
                .Cells.Replace What:="(null)", _
                Replacement:="", _
                LookAt:=xlWhole, _
                SearchOrder:=xlByRows, _
                MatchCase:=False
    
    
            'BOTH LastRow and LastCol WORK
            'Get Last Row & Record Count
    
                intLastRow = oXLSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row  'This Works
                intRecordCount = intLastRow - 1
    
            'Get Last Column
                intLastCol = oXLSheet.Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column 'This Works
                intNextCol = intLastCol + 1
    
    
    
    
    
        'Get SUM of Column strQASumColumn for use in QA
    
            'NONE of the following work.  Note that if I use Select it's for testing so that I can look at Open Excel Sheet and see the Select Range is correct
    
                strSUMRange = strQASumColumn & "2:" & strQASumColumn & intLastRow '  "M2:M2934"
                Set rgSUMRange = .Range(strSUMRange)
                'rgSUMRange.Select
                varSumExcelColumns = Excel.WorksheetFunction.Sum(rgSUMRange) 'Works BUT IS ZERO??
                dblSum = Excel.WorksheetFunction.Sum(rgSUMRange) 'Works but ZERO?
                varSumExcelColumns = Excel.WorksheetFunction.Sum(oXLSheet.Range(strSUMRange))  'Works but Zero
    
    
    
            'Try to use Cells
                 Set rgSUMRange = .Range(.Cells(2, "M"), .Cells(intLastRow, "M"))
                 rgSUMRange.Select
                 varSumExcelColumns = Excel.WorksheetFunction.Sum(rgSUMRange) 'Works but Zero SUM
    
                 Set rgSUMRange = .Range(.Cells(2, intNextCol), .Cells(intLastRow, intNextCol))
                 varSumExcelColumns = Excel.WorksheetFunction.Sum(rgSUMRange) 'Works but Zero
    
                 'Even Hard-coding the numbers does NOT work
                 Set rgSUMRange = .Range(.Cells(2, 13), .Cells(2934, 13)) ' Returns Zero Again
                 'rgSUMRange.Select  ' Does show the correct Range
                 varSumExcelColumns = Excel.WorksheetFunction.Sum(rgSUMRange)
    
                 'Still Zero if I use a smaller range that has contiguous numbers
                 Set rgSUMRange = .Range(.Cells(3, 13), .Cells(7, 13)) ' Returns Zero Again
                 rgSUMRange.Select
                 varSumExcelColumns = Excel.WorksheetFunction.Sum(rgSUMRange)
    
            'All these approaches ERROR
                'varSumExcelColumns = Excel.WorksheetFunction.Sum(.Range(rgSUMRange)) 'Method Range of Object Worksheet Failed
                'varSumExcelColumns = Excel.oXLSheet.WorksheetFunction.Sum(.Range(rgSUMRange)) 'Won't compile
                ' varSumExcelColumns = Excel.WorksheetFunction.Sum("M2:M2934")  'Unable to get the SUM Property of the WorksheetFunction Class
                'varSumExcelColumns = Excel.WorksheetFunction.Sum(Range("M2:M2934")) 'Application defined or object defined error
    
                'dblSum = Excel.WorksheetFunction.Sum("M2:M100") 'ERROR:  Unable to get the SUM Property of the Worksheet function Class
                'dblSum = Excel.WorksheetFunction.Sum(Range("M2:M100")) 'Application defined or --- Error
    
                'varSumExcelColumns = Excel.WorksheetFunction.Sum(Worksheets(strActiveSheet).Range("M2", "M7")) 'ERROR Application Defined or Object Defined Error
    
    
    
    
          'Go to EMPTY Range next to the Last Column
    
                 varSumExcelColumns = Excel.WorksheetFunction.Sum(.Range(.Cells(2, intNextCol), .Cells(intLastRow, intNextCol)))  ' Works for SUM but is wrong Range
                 'THE ABOVE ACTUALLY WORKS, BUT ONLY IF I GO TO OPEN SPREADSHEET AND MANUALLY ENTER NUMBERS INTO THE RANGE AREA ?????????
    
            'Since the above kinda worked, Try setting variables to a Range WITH Number data - Does NOT Work
                 intNextCol = 13
                 intLastRow = 7
                 varSumExcelColumns = Excel.WorksheetFunction.Sum(.Range(.Cells(2, intNextCol), .Cells(intLastRow, intNextCol)))
                 msgbox "SUM:  " & varSumExcelColumns
    
    
            'Test to see if I am still on the Correct Sheet - This WORKS
                 Dim dblCellValue As Double
                 dblCellValue = oXLSheet.Cells(2, 13).Value  'Works
    
    
    
        End With
    
    
    
    
    Exit_Label:
        fnImportFileProcessFilePrep2 = varSumExcelColumns
    
    
        oXLBook.Close SaveChanges:=False  'SaveChanges:=True    'Save (and disconnect from) the Workbook
    
    
    
        oXLApp.Quit                         'Close (and disconnect from) Excel
        Set oXLSheet = Nothing               'Disconnect from all Excel objects (let the user take over)
        Set oXLBook = Nothing
        Set oXLApp = Nothing
    
    Exit Function
    
    HandleError:
    
    
        msgbox "Error During fnImportFileProcessFilePrep2: " & Err.Description
    
        Resume Next
    End Function
    
    Private Sub TestFilePrep()
    Dim strFileNameAndPath As String
    Dim strUseWorksheet As String
    Dim intSUMColumn As Integer
    Dim strSUMColumn As String
    Dim strAddColumnLabel As String
    Dim varAddColumnFixedValue As Variant
    
    Dim dblSUMFromFunction As Double
    
    strFileNameAndPath = "C:\Users\xxxxxxxWITH NULLS2.xlsx"
    strUseWorksheet = "Sheet1"
    intSUMColumn = 13
    strSUMColumn = "M"
    strAddColumnLabel = "SourceFile"
    varAddColumnFixedValue = 77
    
    
    dblSUMFromFunction = fnImportFileProcessFilePrep2(10, -3, strFileNameAndPath, _
    strUseWorksheet, strSUMColumn)
    
    End Sub
    

2 个答案:

答案 0 :(得分:3)

使用:

varSumExcelColumns = oXLApp.WorksheetFunction.Sum(rgSUMRange)

因为您的Excel应用程序在oXLApp对象

中被“表示”

答案 1 :(得分:0)

我认为问题可能(至少部分)是您声明范围变量的方式。我没有在Access中使用VBA,但我在Excel中使用VBA来创建和操作Word文档,我遇到了类似的问题。

当您声明一个范围变量时,您需要指定它是一个Excel范围变量(如果它是如何使用的)。所以,当你

Dim rgUseRange As Range
Dim rgSUMRange As Range

应该是

Dim rgUseRange as Excel.Range
Dim rgSUMRange as Excel.Range

这是必要的,因为Access对象模型也有一个Range对象,但它与Access Range对象(和Word Range对象)不同。

假设除了您正在使用的“本机”对象模型之外的任何对象都是如此。虽然,也可以指定该对象模型。

我当然希望这会有所帮助。

编辑:显然Access中没有Range对象。我还是试着看看它是否有帮助。