Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find maximum rows of the sheet of workbook - vba

Tags:

excel

vba

I want to get the data from the workbook which contain the multiple sheets and dont know which sheet having the data. So need to check the used rows count of the every sheet of the workbook and activate the sheet which contain maximum used rows for getting the data. struct with below code and any suggestion would appreciate.

Sub Maxdatasheet()
Dim wscount As Integer
Dim myArray() As Variant

wscount = ActiveWorkbook.Worksheets.Count

  For i = 1 To wscount
    myArray(i) = Worksheets(i).UsedRange.Rows.Count
    Next
    'need to activate the maximus rows of the sheet
End Sub
like image 844
Ashok Avatar asked Nov 15 '25 06:11

Ashok


2 Answers

A few changes:
- No array, keeping track of what sheet had the maximum instead
- Changed to For Each (even though your code was perfectly fine in that aspect)

Sub Maxdatasheet()
    Dim ws As Worksheet
    Dim MaxRowSheet As Worksheet
    Dim MaxRowCount As Long    ' Do not use Integer, may be too small and cause overflow

    wscount = ActiveWorkbook.Worksheets.Count

    MaxRowCount = 0

    For Each ws In ActiveWorkbook.Worksheets
        If ws.UsedRange.Rows.Count > MaxRowCount Then
            MaxRowCount = ws.UsedRange.Rows.Count
            Set MaxRowSheet = ws
        End If
    Next
    MaxRowSheet.Activate
End Sub
like image 101
Sam Avatar answered Nov 17 '25 21:11

Sam


To get count of used rows from each sheet-

Sub Maxdatasheet()
Dim wscount As Integer
Dim myArray() As Variant

wscount = ActiveWorkbook.Worksheets.Count
ReDim myArray(1 To wscount)

  For i = 1 To wscount
    myArray(i) = Worksheets(i).UsedRange.Rows.Count
    Debug.Print myArray(i)
  Next
End Sub
like image 36
Unknown Avatar answered Nov 17 '25 20:11

Unknown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!