+ Reply to Thread
Results 1 to 2 of 2

Referencing column as a variable using Range?

  1. #1
    Registered User
    Join Date
    08-10-2012
    Location
    Washington
    MS-Off Ver
    Excel 2003
    Posts
    28

    Referencing column as a variable using Range?

    I have found a lot of example of how to use a variable for the row but can't find anything much on using a variable to select the column.

    I have this that works (assigns average from another worksheet, to MyValue, in the current worksheet):
    This works but has hardcoded range
    MyValue = WorksheetFunction.Average(Range("'MyFile.csv'!E2:E100"))

    But I want to use a variable in range. If I was using the variable for the row, it would be easy. I could just use:
    MyValue = WorksheetFunction.Average(Range("'MyFile.csv'!E2:E" & SomeVar))

    But my problem is, I need to use the variable for the column. I have tried cell(r, c) for the range but can't get it to work. I'm sure it's just how I'm using it. I would expect to use cell(2,c) for the E2 part and/or cell(100,c) for the E100 part, where 'c' is a variable. But it's not working.

    I tried:

    MyValue = WorksheetFunction.Average(Range("'MyFile.csv'!" & cells(2,c) & "," & cells(100,c))), where 'c' is a variable, but this doesn't work.

    Can someone show me how the bolded line above would be modified to use a variable to change the column value (i.e. to increment from 'C' to 'E' or 'Z' or any column)? The solution also needs to be able to use a filename, because the data is in a different file.
    Last edited by MikeSD; 08-10-2012 at 06:50 PM.

  2. #2
    Forum Moderator - RIP Richard Buttrey's Avatar
    Join Date
    01-14-2008
    Location
    Stockton Heath, Cheshire, UK
    MS-Off Ver
    Office 365, Excel for Windows 2010 & Excel for Mac
    Posts
    29,464

    Re: Referencing column as a variable using Range?

    Hi,

    One approach would be

    Dim myvalue As Double
    Dim c As Long
    c = 6 'i.e. column F
    myvalue = WorksheetFunction.Average(Range("'MyFile.csv'!A2:A100").Offset(0, c - 1))
    Richard Buttrey

    RIP - d. 06/10/2022

    If any of the responses have helped then please consider rating them by clicking the small star icon below the post.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1