Microsoft Excel - setting a variable range in vba

Asked By jon macintosh
22-Sep-08 02:07 PM

please can you help me to create a range, using vba - the top left hand corner of the range is fixed, but the number of columns and rows of the range change depending on the data. 

Specifically, I cant figure the coding to create a range which starts at cell c6, and is x colums wide and y rows high, where x is the number in cell a1, and y is the number contained in cell a2.

Any advice much appreciated!

Creating a VBA Range  Creating a VBA Range

23-Sep-08 04:02 PM

I do this all the time using the Offset method of the range.  Here's some sample code:

Sub RangeTest()
    Dim rng As Range
    Dim rowOffset As Long
    Dim columnOffset As Long
    
    ' grab offets as width - 1 and height - 1
    rowOffset = Range("A2").Value - 1
    columnOffset = Range("A1").Value - 1
    
    ' set the "upper-left corner"
    Set rng = Range("C6")
    
    ' using offset and a reference to the range itself, "Stretch" the range
    Set rng = Range(rng, rng.Offset(rowOffset, columnOffset))
    
    MsgBox "The new Range is: " & rng.Address
    
    Set rng = Nothing
End Sub

Is this what you're looking for?

 

Good luck,

Brendon

create the range based on data : Use Dynamic or named ranges  create the range based on data : Use Dynamic or named ranges

24-Sep-08 07:10 PM

Dynamic Ranges
--------------
It is often useful to create a name that refers to a range of cells, where the range depends on the content of the cells.  For example, you may want a name that refers to the first N non-blank entries in column A.   Excel's Name tool allows you to do this.  For example, creating a name called DynaRange, referring to

=OFFSET(Sheet1!$A$1,0,0,COUNTA(Sheet1!$A:$A),1)

If the first 20 rows of column A contain data (and the rest are blank), DynaRange will refer to the range A1:A20

See the on-line help for the =OFFSET function for a description of the arguments.  Setting the Width argument to 2 will allow us to use this name in a =VLOOKUP function

=OFFSET(Sheet1!$A$1,0,0,COUNTA(Sheet1!$A:$A),2)

Then, call VLOOKUP with the DynaRange argument for the lookup range:

=VLOOKUP(C1, DynaRange, 2)

As data is added to columns A and B, the range search by VLOOKUP will extend to include the new data. Refer http://www.cpearson.com/excel/named.htm for details.

Named Ranges:
-------------

To to create a macro to automatically create named ranges for each sheet within the workbook. I want the named range to equal the sheet name if possible. The actual range for each sheet will always remain the same.
Here's an example, naming the range A1:B2 on each sheet.

Sub nameRanges()
   Dim sht As Worksheet
   For Each sht In ThisWorkbook.Worksheets
       ActiveWorkbook.Names.Add Name:=sht.Name, _
           RefersTo:=sht.Range("a1:b2")
   Next sht
End Sub

Example in VB:

Private Sub LoadAndFormatData(ByVal dr As SqlDataReader)
    Dim i, j As Integer

    ' Copy the data in from the SqlDataReader.
    i = 1
    While dr.Read
        i = i + 1
        For j = 0 To 1
            xlSheet.Cells(i, j + 1) = dr(j).ToString()
        Next j
    End While
    dr.Close()

    ' Format the columns.
    DirectCast(xlSheet.Columns(1), _
        Excel.Range).AutoFit()

    With DirectCast(xlSheet.Columns(2), _
        Excel.Range)
        .NumberFormat = "0.00"
        .AutoFit()
    End With
End Sub

-Paresh

Create New Account
help
storeinto exccl Hello Sir, , i kept the table into dt variable i want export into excel sheet button click i try this sqlconnection con = new sqlconnection("datasource = "filename""); con.open(); sqldataadapter from purchaseOrder", con); datatable dt = new datatable da.fill(dt); . . this datatable automatically created one excel sheet and stored to worksheet while pressing above button thanks Bhanu prakash Untitled document Try this code for exporting data to excel: Add the reference in your project. Right click on the project - > add reference Now from the COM tab add two references 1. Microsoft Office 12.0 Object Library 2. Microsoft Excel 12.0 Object Library using Excel = Microsoft.Office.Interop.Excel; private void btnExport_Click( object sender, EventArgs e) { / / creating Excel Application Excel. _Application
Excel Pie chart not reflecting the right values. Hi! I am trying to generate a pie chart using excel automation. The sourece data for the chart is coming from a SQL query. The pie Type .Missing).Value2 = sqlDrPie.GetValue(0).ToString(); objSheet3.get_Range( "A" + R, Type .Missing).BorderAround(8, Microsoft.Office.Interop.Excel. XlBorderWeight .xlThick, Microsoft.Office.Interop.Excel. XlColorIndex .xlColorIndexAutomatic, Type .Missing); objSheet3.get_Range( "B" + R, Type .Missing).Value2 = sqlDrPie.GetValue(1).ToString objSheet3.get_Range( "B" + R, Type .Missing).BorderAround(8, Microsoft.Office.Interop.Excel. XlBorderWeight .xlThick, Microsoft.Office.Interop.Excel. XlColorIndex .xlColorIndexAutomatic, Type .Missing); / / objSheet3.get_Range("C" + R, Type
Copy data from database to excel sheet I have ac# function that is connecting the database and fetching data from there click on the project - > add reference Now from the COM tab add two references 1. Microsoft Office 12.0 Object Library 2. Microsoft Excel 12.0 Object Library using Excel = Microsoft.Office.Interop.Excel; private void btnExport_Click( object sender, EventArgs e) { / / creating Excel Application Excel. _Application app = new Microsoft.Office.Interop.Excel. Application (); / / creating new WorkBook within Excel
Export DataTable to Excel Hello everyone, My name is Stelios Lazaris and I am a postgraduate student in Greece at the university of Patras. I recently read an article about Dynamic ASP.NET Excel Workbooks in C by Peter Bromberg. I followed his guidelines and managed to exit from Excel successfully. My problem is that I have written a class that takes as input a DataTable and writes it on a Excel Workbook. In the initial version I didn't use the Excel.Range object and Excel disappeared from Task Manager as one would expect. But when I used the Excel.Range object, Excel refuses to close. I also noticed that the zombie Excel process terminates only if I
mistake, but currently I am reading the logfiles placed under "c: \ program files \ common files \ microsoft shared \ web server extensions \ 12 \ logs". I don't find any relavant information regarding authentication SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) bei System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) bei System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) bei System EXE (0x0980) 0x0988 Windows SharePoint Services Database 880i High . . .tem.Data.SqlClient.SqlConnection.Open() bei Microsoft.SharePoint.Utilities.SqlSession.OpenConnection() 03 / 04 / 2010 13:53:11.35 OWSTIMER.EXE (0x0980) 0x0988 13:53:11.59 OWSTIMER.EXE (0x0980) 0x0988 Windows SharePoint Services Database 880k High bei Microsoft.SharePoint.Utilities.SqlSession.ExecuteReader(SqlCommand command, CommandBehavior behavior) bei Microsoft.SharePoint.Administration.SPConfigurationDatabase.FetchId(QualifiedObjectName qName) bei Microsoft.SharePoint.Administration.SPConfigurationDatabase.GetObject(String name, Guid parentId, Type type) bei Microsoft.SharePoint.Administration.SPConfigurationDatabase.get_Farm() bei Microsoft.SharePoint.Administration.SPFarm.FindLocal(SPFarm& farm, Boolean& isJoined) bei Microsoft.SharePoint.Administration.SPFarm.get_Local() bei