计算多张纸上的数据

时间:2018-12-27 15:56:33

标签: excel vba excel-vba

我有这段代码,我想用一列数据计算单元格的数量。 但是挑战在于,我必须从所有工作簿中计算出这些单元格。 因此,例如,我有2个工作簿:WB1和WB2。我有一个工作表WS1,其数据在A1,A2,A3,A4中,而工作表WS2,其数据在A1,A2中。因此,我的输出应显示为6。但是我遇到了麻烦,该如何计算呢?我有以下代码:

Option Explicit

Private Sub CommandButton1_Click()

Dim paths(), wbs() As Workbook
Dim x As Integer
Dim sh, rn, k
paths = Application.GetOpenFilename(FileFilter:="Excel Files (*.XLSX), *.XLSX", MultiSelect:=True, Title:="Please browse all the Rawdata files")
For x = 1 To UBound(paths)
    ReDim wbs(UBound(paths))
    Set wbs(x) = Workbooks.Open(paths(x))

    Set sh = wbs(x).Sheets("Role ID - Description")
    Set rn = sh.UsedRange
    k = rn.Rows.Count + rn.Row - 1 - 1
    wbs(x).Close
Next

End Sub

1 个答案:

答案 0 :(得分:2)

您不是要为工作簿的每一页维护计数器(例如k = k + 1迭代1)。在工作簿中,您需要以下内容:

dim i as long, k as long, lr as long
With Workbook("blah")
    For i = 1 to .sheets.count
        With .Sheets(i)
            lr = .cells(.rows.count,1).end(xlup).row
            k = k + lr
        End with
    Next i
    'output k to some destination
    k=0
End with

编辑1:

根据Kubie的建议添加国家场景(未试用):

dim i as long, k as long, cnta as long
With Workbook("blah")
    For i = 1 to .sheets.count
        With .Sheets(i)
            cnta = application.counta(.columns(1))
            k = k + cnta
        End with
    Next i
    'output k to some destination
    k=0
End with