在Array Excel VBA中使用Sums

时间:2018-04-22 02:48:34

标签: excel excel-vba vba

我有一个由变量工作簿中的静态单元格组成的数组。 当我将它们复制到活动工作簿时,单元格数量比原始数组少。因此,阵列中的39个单元被卷成33个单元作为示例。 有没有办法像这样对数组中的单元格求和?
Array("C6" + "C7","C8","C9")? 示例表

来自外部工作簿的来源:

enter image description here

生成活动工作簿的结果: enter image description here

我真正想要的结果如下: enter image description here 在我的代码中,我正在尝试修改cls数组,因此"C6"将为"C6+C7"或其他内容:

Option Explicit

Sub ImportData()

Dim B1 As Workbook
Dim B2 As Workbook
Dim S1 As Range
Dim cls As Variant, LR As Long, i As Long

Set B1 = ActiveWorkbook

cls = Array("C3", "C4", "C5", "C6", "C7", "C10", "C11", "C12", "G12")
With Application.FileDialog(msoFileDialogOpen)
    .Filters.Clear
    .Filters.Add "Excel Files", "*.xlsx*;*.xlsm*;*.xlsa*;*.xm*"
    .AllowMultiSelect = False
    .Show
    If .SelectedItems.Count > 0 Then
        Workbooks.Open .SelectedItems(1)
        Set B2 = ActiveWorkbook
        Set S1 = Application.InputBox(prompt:="Select source sheet (select any cell)", Title:="Source sheet", Default:="A1", Type:=8)
        With B1.Sheets("Sheet2")
            For i = LBound(cls) To UBound(cls)
                .Range("C4").Offset(, i).Value = S1.Parent.Range(cls(i)).Value
            Next i
            .Range("C4:K4").EntireColumn.AutoFit
        End With
        B2.Close False
    End If
End With

End Sub

提前致谢。

1 个答案:

答案 0 :(得分:1)

这是一种方法,它演示了描述和函数中使用的单元格范围的四种变体。

Option Explicit

Sub sumComplex()
    Dim i As Long, cls As Variant

    cls = Array("A1:A3", "B2,B4,B6", "C2:C3,C5", "D4")

    With Worksheets("sheet9")
        For i = LBound(cls) To UBound(cls)
            Debug.Print Application.Sum(.Range(cls(i)))
        Next i
    End With
End Sub

enter image description here

'results
 6 
 12 
 20 
 99 

这可以通过以下方式应用于您的代码。

cls = Array("C3", "C4", "C5", "C6:C7", "C10", "C11", "C12,G12")
...
    With B1.workSheets("Sheet2")
        For i = LBound(cls) To UBound(cls)
            if S1.Parent.Range(cls(i)).count > 1 then
                .Range("C4").Offset(0, i).Value = _
                    application.sum(S1.Parent.Range(cls(i)))
            else
                .Range("C4").Offset(0, i).Value = S1.Parent.Range(cls(i))
            end if
        Next i
        .Range("C4").resize(1, i).EntireColumn.AutoFit
    End With