Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UsedRange.Count counting wrong

Tags:

excel

vba

Summary: I'm taking a row of data from one sheet and pasting it into another, however the sheet would be a daily use kind of thing where new data is just entered below old data.

Problem: On each new run, 7 is consistently added to the UsedRange.Count. For example: on one run the UsedRange.Count will be 7; the next time I run through the function the count will be 14.

What I'm Looking For: Why is this the case and is there a way to help UsedRange be more accurate

-I've included the entire Function for references' sake.

Function eftGrabber()

        Dim usedRows As Integer
        Dim i As Integer

        ChDir "\\..."       

        Workbooks.Open Filename:= _
        "\\...\eftGrabber.xlsm"

        usedRows = Sheets("EFT").UsedRange.Count

        Windows("Data").Activate

        Sheets("DataSheet").Range("A11").EntireRow.Copy

        Windows("eftGrabber").Activate

        Sheets("EFT").Range("A" & usedRows + 1).Select

        ActiveSheet.Paste

        i = usedRows

        Do                            'THIS LOOP DELETES BLANKS AFTER POSTING NEW LINES

            Range("A" & i).Select

            If Range("A" & i) = "" Then

                ActiveCell.EntireRow.Delete

            End If

              i = i - 1

        Loop Until i = 1

        Windows("eftGrabber").Activate

        ActiveWorkbook.Save

  Windows("eftGrabber").Close

End Function

Let me know if I've left out any important details. Thanks in advance!

like image 586
Mike Kellogg Avatar asked Aug 09 '12 15:08

Mike Kellogg


2 Answers

Change: usedRows = Sheets("EFT").UsedRange.Count

To: usedRows = Sheets("EFT").Range("A" & Sheets("EFT").Rows.Count).End(xlUp).Row

Where "A" can be changed to whichever row you wish to count the total number of columns.

There is a danger in using UsedRange because it factors in such things and formatted cells with no data and other things that can give you unexpected results, like if you are expecting your data to start in Range("A1"), but it really starts in another range!

I will say, however, that If you really wish to use UsedRange, your code above is still wrong to get the rows. Use this instead UsedRange.Rows.Count or to get the last absolute cell of the UsedRange, use UsedRange.SpecialCells(xlCellTypeLastCell).Row

like image 184
Scott Holtzman Avatar answered Sep 26 '22 08:09

Scott Holtzman


This two line do the magic

  usedCol = ThisWorkbook.ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
  usedRow = ThisWorkbook.ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

For more info visit Microsoft's site

http://msdn.microsoft.com/en-us/library/office/ff196157.aspx

like image 25
Hari Das Avatar answered Sep 22 '22 08:09

Hari Das