繁体   English   中英

Excel VBA SUM返回零或错误

[英]Excel VBA SUM returning zero or error

我试图通过只关注与Excel.WorksheetFunction.Sum有关的一个问题来简化先前的文章。 我显然不知道如何使用此功能,因为我一直将结果归零或抛出错误。

我根本无法使它正常工作,而且我已经将其工作了三天(从字面上看),并且已经进行了近百次不同的测试。 尽管我对Access VBA的理解很好,但是我是自学成才的,我认为我缺少一些关键概念,这在Excel中使我丧命。

下面的代码来自我已经完成的测试/调试,文档说明了每个不同版本的结果。 子调用函数(这就是问题所在)。

几点:

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

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

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

  3. 暗示我之前的工作没有“完全合格”,所以我使用With Bloc构建了它。 但是,很可能我没有正确执行此操作。

任何指导将不胜感激-特别是如果您能认真地解释我在这里缺少的概念。


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

采用:

varSumExcelColumns = oXLApp.WorksheetFunction.Sum(rgSUMRange)

因为您的Excel应用程序已在oXLApp对象中“表示”

我认为问题可能(至少部分是)您声明范围变量的方式。 我没有在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对象。 我仍然会尝试这样做是否有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM