简体   繁体   中英

Looping through cells by column and converting each current cell value to new cell values through a function (Excel VBA)

I'm trying to solve a problem that asks to convert current dollar amounts to constant dollar amounts using the formula (constant$ = current$/(CPI-U*0.01)).

I'd like to use excel vba to loop through each cell in a column first and then move over to the next column after reaching a cell at the bottom of column with no data (using offset?). The loop doesn't include the first or last column (year & CPIU) and each iteration inputs the current cell dollar value into a formula and replaces the current cell dollar value with the updated constant dollar value (not putting it into a different table).

For example, if cell value for B2 is 11116 and the corresponding CPIU for the year is 41.8, then input 11116 into function =QUOTIENT(11116, PRODUCT(41.8,0.01)). Replace 11116 with 26593 in cell B2.

I'd like to also have the CPIU cell references to update with each loop iteration . For example, CPIUs are in column "F" so if its cell B2 then F2 should be selected, C3 to F3 and so on.

This is for the following excel function example:

ActiveCell.Formula = "=QUOTIENT(B2,PRODUCT(F2,0.01))"

*B2 would be replaced with loop iterator but still trying to figure out how to update F column with each iteration

This is the table: Data Table *Range A1:F17 (includes headers)

Here's the beginning of the vba procedure loop:

Public Sub LoopThroughAllTableCells()
    Dim convertedValue As Long

    For Each c In Worksheets("Sheet1").Range("B2:E17").Cells

    Next   
End Sub

*Not sure if this current loop is the right way to loop through each cell in 1 column and then move over to the next column.

Apologize for the lengthy post, but having trouble fitting the pieces together. Any help would be much appreciated!

Try this:

Public Sub LoopThroughAllTableCells()

Range("B2").Select 'position of the first cell and column you want to check
Do Until ActiveCell.Column = 6
    Do Until ActiveCell.Value = ""
        ActiveCell.Value = ActiveCell.Value / (Range("F" & ActiveCell.Row).Value * 0.01)
        ActiveCell.Offset(1, 0).Select
    Loop
    Cells(2, ActiveCell.Column + 1).Select
Loop

End Sub

If you need your values to be Integer, with no decimals then change this line:

ActiveCell.Value = ActiveCell.Value / (Range("F" & ActiveCell.Row).Value * 0.01)

And use this line:

ActiveCell.Value = Application.WorksheetFunction.Round(ActiveCell.Value / (Range("F" & ActiveCell.Row).Value * 0.01), 0)

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