0

I am using VB.net code to manipulate Excel documents. I'm trying to grab a range of cells contained in a single specific row. I don't know the specific end cell, I just need All the cells that contain values in that row.

Here is a basic example of what i've been doing up to this point:

Dim rngRange as Excel.Range

Dim wksXLWorksheet As Excel.Worksheet

rngRange = wksXLWorksheet.Range("A1").EntireRow

I know that row containing the Range "A1" (which is a single cell) is the row that I want, and so I use the EntireRow property to return the entire row. It returns all the cells, including the unused ones, so over 16k in cells, most of them empty.

How can choose a range with only the used the Cells? I don't want to use UsedRange because that grabs everything, I only want the one row, and only up to where the cells no longer contain data.

Also, if i select a limited range like this, will it have more or less impact on resources? I was assuming it would have less impact selecting the small range, but I could be wrong.

2 Answers 2

1

Use .End property, e.g. Range("A1").End(xlToRight).

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that was simple. I had looked at the end property in some online documentation but I ended up skipping over it when it didn't work the way I expected; that was before I got to my current understanding of ranges.. Thanks!
@meltdownmonk -> While this is a good answer, a better solution might be this: rngRange = wksXLWorksheet.Cells(1, wksXLWorksheet.Range("A" & wksXLWorksheet.Columns.Count).End(xlToLeft).Column) This syntax moves from the last column to the left to find the real row end, were as the starting from cell A1 and moving to the right xlToRight will stop at the first random blank cell that shows up, should there be any.
I don't think this completely answered the question... This only returns the last used cell in the row, not all the cells.
0

The Excel.Application object has an Intersect method and the worksheet has a UsedRange property.

Dim rngRange as Excel.Range
Dim wksXLWorksheet As Excel.Worksheet
Dim xlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application()

rngRange = Excel.Intersect(wksXLWorksheet.Range("1:1"), wksXLWorksheet.UsedRange)

Alternately, define the range with the start and end points while qualifying the Cells that make up the Range.

Dim rngRange as Excel.Range
Dim wksXLWorksheet As Excel.Worksheet

rngRange = wksXLWorksheet.Range(wksXLWorksheet.Range("A1"), wksXLWorksheet.Range("XFD1").End(xlToLeft))

Comments

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.