Excel VBA将某些列的最后一个单元格汇总为“摘要”工作表

时间:2017-06-06 00:14:54

标签: excel vba excel-vba

我正在尝试使用以下代码找到Internet,将工作表(发票)汇总到“摘要表”中。我没有成功修改它以选择F列(总金额)中的最后一个单元格,它代表每张发票的总数。

F栏中的总数根据销售的商品而有不同的行号。

请帮助我更新代码,从上一个单元格中选择总值,在F列中选择值。

谢谢!

Sub Summary_All_Worksheets_With_Formulas()
Dim Sh As Worksheet
Dim Newsh As Worksheet
Dim myCell As Range
Dim ColNum As Integer
Dim RwNum As Long
Dim Basebook As Workbook

With Application
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
End With

'Delete the sheet "Summary-Sheet" if it exist
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Worksheets("Summary-Sheet").Delete
On Error GoTo 0
Application.DisplayAlerts = True

'Add a worksheet with the name "Summary-Sheet"
Set Basebook = ThisWorkbook
Set Newsh = Basebook.Worksheets.Add
Newsh.Name = "Summary-Sheet"

'The links to the first sheet will start in row 2
RwNum = 1

For Each Sh In Basebook.Worksheets
    If Sh.Name <> Newsh.Name And Sh.Visible Then
        ColNum = 1
        RwNum = RwNum + 1
        'Copy the sheet name in the A column
        Newsh.Cells(RwNum, 1).Value = Sh.Name

        For Each myCell In Sh.Range("A1,A2,C3,E3,C4,E4,C5,E5")  '<--Change the range
            ColNum = ColNum + 1
            Newsh.Cells(RwNum, ColNum).Formula = _
            "='" & Sh.Name & "'!" & myCell.Address(False, False)
        Next myCell

    End If
Next Sh

Newsh.UsedRange.Columns.AutoFit

With Application
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
End With
End Sub

1 个答案:

答案 0 :(得分:0)

您无需遍历单元格即可找到您的总金额&#34;。我按如下方式修改了部分代码:

    If Sh.Name <> Newsh.Name And Sh.Visible Then
      ColNum = 1
      RwNum = RwNum + 1
      'Copy the sheet name in the A column
      Newsh.Cells(RwNum, 1).Value = Sh.Name

      'put this declaration on top
      Dim CellsArray() As String
      Dim RangeString As String
      Dim intCount As Integer

      'your collection of ranges
      RangeString = "A1,A2,C3,E3,C4,E4,C5,E5"

      'split them into array
      CellsArray = Split(RangeString, ",")

      'loop through your array
      For intCount = LBound(CellsArray) To UBound(CellsArray)

        ColNum = ColNum + 1
        Newsh.Cells(RwNum, ColNum).Formula = _
        "='" & Sh.Name & "'!" & CellsArray(intCount) '<- access each range in array

      Next intCount


      'Find last row in the column: "Total Amount"
      LastRow = Sh.Cells(Sh.Rows.Count, "F").End(xlUp).Row

      'Assign that cell to myCell
      Set myCell = Sh.Range("F" & LastRow)

      'total
      ColNum = ColNum + 1
      Newsh.Cells(RwNum, ColNum).Formula = _
      "='" & Sh.Name & "'!" & myCell.Address(False, False)

    End If

编辑:我在请求中间添加了循环周期