使用VB在Excel中汇总列

时间:2014-09-05 23:55:07

标签: vb.net excel sum

好的,我在excel中有一个直接的2-d数据块:第1行和第1列是标签,其余是数字。我现在的任务是将每列的总和放在下面的第一个空单元格(行)中。

虽然我的练习数据集具有已知维度,但我将使用此程序的实际数据集将具有可变数量的行和列。为此,我不能只说" = SUM(B2:B20)"因为最后一个填充的单元格不会一直是B20(例如)。我认为,总计每列的最简单方法是FOR..NEXT循环,但我不能让VS接受求和公式。这是我到目前为止所得到的:

  `With xlWsheet2 'check for last filled row and column of transposed data'
        If xlApp.WorksheetFunction.CountA(.Cells) <> 0 Then
            lRow2 = .Cells.Find(What:="*",
                               After:=.Cells(1, 1),
                               LookAt:=Excel.XlLookAt.xlPart,
                               LookIn:=Excel.XlFindLookIn.xlFormulas,
                               SearchOrder:=Excel.XlSearchOrder.xlByRows,
                               SearchDirection:=Excel.XlSearchDirection.xlPrevious,
                               MatchCase:=False).Row
        Else : lRow2 = 1
        End If

        If xlApp.WorksheetFunction.CountA(.Cells) <> 0 Then
            lCol2 = .Cells.Find(What:="*",
                               After:=.Range("A1"),
                               LookAt:=Excel.XlLookAt.xlPart,
                               LookIn:=Excel.XlFindLookIn.xlFormulas,
                               SearchOrder:=Excel.XlSearchOrder.xlByRows,
                               SearchDirection:=Excel.XlSearchDirection.xlPrevious,
                               MatchCase:=False).Column
        Else : lCol2 = 1
        End If


        lastcell2 = xlWsheet2.Cells(lRow2, lCol2) 'defines last row, column of transposed data'
        emptyRow1 = xlWsheet2.Rows(lRow2).Offset(1) 'defines the first empty row'


        'add in cell of SUM underneath each column'
        For i As Integer = 2 To lCol2
            colTop = xlWsheet2.Cells(2, i)
            colBot = xlWsheet2.Cells(lRow2, i)

            ELtotal = xlWsheet2.Range(emptyRow1, i)
            ELtotal = .Sum(.Range(colTop, colBot))
        Next i
    End With

` 现在,ELtotal语句曾经是一个长线,但我试图看看VS有什么问题。它在第一个中断,.Range(emptyRow1,i)。我尝试过的那个方程式的其他迭代是不被接受的:

.Range(emptyRow1, I).Formula = "=SUM(colTop, colBot)"
.Range(emptyRow1, I).Formula = "=SUM(.cells(2,i), (lRow2,i))"
.Range(emptyRow1, I).Formula = .sum(.range(colTop, colBot)
.Range(emptyRow1, I).Value = etc...

ad inifintum

PS-我对此很陌生,所以我可能以错误的方式处理整个过程...

3 个答案:

答案 0 :(得分:0)

这个公式将在这种情况下总结两个完整的列A和B:

= sum($A:$B)

如果标题可能被解释为可能对总和有贡献的数值,则应将公式修改为

= sum($A:$B) - sum($A$1:$B$1)

答案 1 :(得分:0)

根据你告诉我的关于行和列标题的内容,我相信这段代码会做你想要的,即在下面的第一个空单元格中放一个列和。

Sub find()   
 Dim lastrow As Long, lastcol As Long, thiscol As Long

    lastrow = Cells(Rows.Count, 1).End(xlUp).Row
    lastcol = Cells(1, Columns.Count).End(xlToLeft).Column
    For thiscol = 2 To lastcol
        Cells(lastrow + 1, thiscol).Select
        ActiveCell.Value = WorksheetFunction.Sum(Range(Cells(1, ActiveCell.Column), ActiveCell))
    Next
    End Sub

祝你好运。

答案 2 :(得分:0)

为了使用DataGridView中所有数字列的总和导出到Excel,请在表单中添加一个按钮,并在其click事件中添加以下代码: -

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
    '--- Export to Excel -------------------------------------------------
    Dim xlApp As Excel.Application
    Dim xlWorkBook As Excel.Workbook
    Dim xlWorkSheet As Excel.Worksheet
    Dim misValue As Object = System.Reflection.Missing.Value
    Dim i As Integer
    Dim j As Integer
    Dim datarange As Excel.Range

    Dim save_file As New SaveFileDialog
    'give its extension
    ''save_file.Filter = "xls files (*.xls)|*.xls|All files (*.*)|*.*"
    'save_file.Filter = "xls files (*.xls)|*.xls"
    save_file.Filter = "xls files (*.xls)|*.xls|Excel 2007|*.xlsx"
    ''Select xls
    save_file.FilterIndex = 2
    save_file.FileName = "My_excel_report_"
    save_file.RestoreDirectory = True

    Try
        If save_file.ShowDialog() = DialogResult.OK Then
            xlApp = New Excel.ApplicationClass
            xlWorkBook = xlApp.Workbooks.Add(misValue)
            xlWorkSheet = xlWorkBook.Sheets("sheet1")

            For x = 0 To DataGridViewSummary1.ColumnCount - 1
                xlWorkSheet.Cells(0 + 1, x + 1) = _
                DataGridViewSummary1.Columns(x).HeaderText
            Next

            For i = 0 To DataGridViewSummary1.RowCount - 1
                For j = 0 To DataGridViewSummary1.ColumnCount - 1
                    If IsDate(DataGridViewSummary1(j, i).Value) Then
                        'MsgBox("The cell value is date")
                        xlWorkSheet.Cells(i + 2, j + 1) = FormatDateTime(CDate(DataGridViewSummary1(j, i).Value.ToString), DateFormat.ShortDate)
                        xlWorkSheet.Cells(i + 2, j + 1).HorizontalAlignment = Excel.Constants.xlCenter
                        xlWorkSheet.Cells(i + 2, j + 1).VerticalAlignment = Excel.Constants.xlCenter
                    Else
                        xlWorkSheet.Cells(i + 2, j + 1) = _
                            DataGridViewSummary1(j, i).Value.ToString()
                    End If
                Next
            Next

            datarange = xlWorkBook.ActiveSheet.UsedRange
            datarange.Font.Name = "Consolas"
            datarange.Font.Size = 10
            '--- added on 07/09/2016 -------------------------------------------------------------------
            Dim lastrow, lastcol As Long
            With xlWorkSheet
                lastcol = .Cells(1, .Columns.Count).End(Excel.XlDirection.xlToLeft).Column
                lastrow = .Range("A" & .Rows.Count).End(Excel.XlDirection.xlUp).Row
            End With
            'MessageBox.Show("The last column in Sheet1 which has data is " & lastcol)
            'MessageBox.Show("The last row in Col A of Sheet1 which has data is " & lastrow)

            For i = 2 To lastcol
                If IsNumeric(xlWorkSheet.Cells(lastrow, i).Value) Then
                    xlWorkSheet.Cells(lastrow + 1, i).Select()
                    xlWorkSheet.Cells(lastrow + 1, i).Value = xlApp.WorksheetFunction.Sum(xlWorkSheet.Range(xlWorkSheet.Cells(1, i), xlWorkSheet.Cells(lastrow + 1, i)))
                End If
            Next i
            xlWorkSheet.Columns.AutoFit()
            '----------------------------------------------------------------------------------------------
            xlWorkSheet.SaveAs(save_file.FileName)  'sd.filename reurns save file dialog path
            xlWorkBook.Close()
            xlApp.Quit()
            releaseObject(xlApp)
            releaseObject(xlWorkBook)
            releaseObject(xlWorkSheet)
             '--------------------------------------

            Dim proc As Process = Nothing
            Dim startInfo As New ProcessStartInfo
            startInfo.FileName = "EXCEL.EXE"
            startInfo.Arguments = save_file.FileName
            Process.Start(startInfo)
        End If
            Catch ex As Exception
        MessageBox.Show(ex.ToString)
        'GlobalErrorHandler(ex)
    End Try
End Sub