0

I want to count the number of cells with data in a column.

I have to count these cells from all the workbooks.

For example, I have 2 workbooks: WB1 and WB2.

  • Worksheet WS1 with data in A1, A2, A3, A4
  • Worksheet WS2 with data in A1, A2.
  • My output should show 6.

How can I count this?

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
  • 1
    what kind of "trouble" do you have? Commented Dec 27, 2018 at 16:02

1 Answer 1

3

You are not maintaining your counter from sheet to sheet for a workbook (e.g., k = k + 1 to iterate by 1). Inside of your workbook you would want something such as:

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

Edit1:

Adding counta scenario per Kubie's recommendation (untested):

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
Sign up to request clarification or add additional context in comments.

2 Comments

since the goal appears to be counting the number of cells with data, maybe should use CountA instead of finding last row for each sheet? (unless no rows are blank)
@Kubie Good point; i had assumedfrom the OP that the lines were contiguous, per the example, which wouldn't necessarily be correct. The same scenario where k is maintained would exist... i'll add your scenario, too, just to be safe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.