簡體   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