简体   繁体   中英

Excel VBA - How to change a cell reference to the second last and last column

My first column consists of the currency names and the column data are monthly exchange rates (with the first row as month names).

Every month, I add a new column with the latest exchange rates. I need to amend the cell references of last month's rate and this month's rate to the second last and last column of the sheet. Is there any code for this?

Thank you

lLastColumn = Cells(1, Columns.Count).End(xlToLeft).Column

This will give the last column assuming the header is in first row. Else, change first argument accordingly

Columns.Count give the total number of columns in the worksheet (which is 16384 in the new Excel formats)

Cells(1, Columns.Count) will give the range of cell in last column in the first row

Cells(1, Columns.Count).End(xlToLeft) will give the range of last non-blank column in the first row. It simulated Ctrl+Left key

Finally, Cells(1, Columns.Count).End(xlToLeft).Column will give the column number of last column in the header

You can then refer other data in last column using Cells(i, lLastColumn)

You don't need code for this. With a very small change to your setup you can use this function.

=INDEX(Sheet1!$A$1:$ZZ$1000, MATCH($A3,Sheet1!$A:$A,0),MATCH(MAX(Sheet1!$1:$1),Sheet1!$1:$1,0))

The required change is to enter dates in the first row of your sheet. (I refer to it as Sheet1 but it could be any name.) To make a caption like "January", enter 1/1/2021 and format the cell as custom mmmm . Use the format mmm yy to display "Jan 21" etc. Having such a date in the first column - that would be column B - use this formula to write subsequent column headers: =EDATE(B1,1) and copy to the right.

In place of Sheet1:$A$1:$ZZ$1000 I would use a dynamic named range. I would use part of that range or an independently declared second named range instead of Sheet1:$1:$1) but that is largely a matter of taste.

Now, MAX(Sheet1:$1:$1) returns the largest (latest) date in row 1. MATCH(MAX(Sheet1:$1,$1):Sheet1,$1:$1,0) returns the column of that date and MATCH(MAX(Sheet1:$1,$1):Sheet1,$1:$1,0)-1 would be the column before that, for the month before.

MATCH($A2,Sheet1:$A,$A,0) returns the row number of a match for A2 in column A of Sheet1. Of course, that's where you have the currencies and one of these must be in A2 of the sheet on which you have the formula, which can't be on the same sheet while INDEX specifies all of that sheet. So, the formula will return the rate from the latest column. As you add another column the formula automatically takes the latest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM