Discussion Locked

Excel VBA problem

0 helpful
7 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I have an excel spreadsheet with an unknown number of rows (the number changes as the sheet is used). I want a macro that will determine how many rows are being used and will select only those rows. I know the starting row, and I can get the numberof rows being used easily with the CountA() function, but I keep getting an Type Missmatch error when I use
Rows.(A5:rnge).Select
or any other similar conbination I could think of. Is there any way around this problem?

Thanks
M.R.Chambers

7 replies

by keith.hall1

Public Sub selectUsed()
Dim n As Integer
Dim ws As Worksheet

Set ws = Application.ActiveSheet
n = ws.UsedRange.Rows.Count
Rows("1:" & CStr(n)).Select
Selection.Copy
End Sub

Regards

Keith Hall

by csanosi

Here is what I usually use...

Dim strRow As String
Dim intRow As Integer

intRow = ActiveCell.SpecialCells(xlLastCell).Row
strRow = "1:" & Trim(Str(intRow))
Rows(strRow).Select
Selection.Copy

by ruuda

There are a number of ways to count the rows that are "used' in a spreadsheet.
1) assumption there are no empty rows, you could look for the current region, this will give you a range as result. from there you can get the Row count... example:
DimMyRange as Excel.Range
Dim iRow as double Dim iRows as double
set MyRange=Activesheet.Cells(5,1).CurrentRegion
'iRows then will give you the number of rows in this Range....
iRows=MyRange.Rows
If after this you want to select this, just do:
Rows("5:" & iRows).select (or .Copy) or whatever you need.
2) on the assumption that there are empty rows in the range, just goto the last row in the sheet (ie: row= 65536 in excel97)
Activesheet.cells(65536,1).select
'and work your way up to the first row with anything in the first cell of that row...
activecell.end(xlup).row 'this will give you the row number of the LAST row with data...
so use this as follows:
iRows=activesheet.cells(65536,1).end(xlup).row
then set MyRange=range("5:" & iRows)
MyRange.copy (or MyRange.select)

This discussion is closed to new replies.