简体   繁体   中英

Excel 2007 using VBA write formula to merged cells

I have a list of values starting at G11 and extending a variable length down column G. I have a string array which contains the addresses of ranges of the G column data to be averaged. In the H column starting at H11 I have merged cells where I want the averaged values to appear. The number of G column cells to be averaged together also varies. The following code I tried failed since the formula was entered as is, rather than having the ranges(i) array value placed into the formula.

For i = 0 To range_num
    ActiveCell.Formula = "=AVERAGE(ranges(i))"
Next i

ranges() contains the ranges (in string form) to be averaged. And for example:

ranges(i) = "G11:G15"

for i = 0 and range_num is the number of averages that will be done.

Each G column value is only included in 1 average, each group of values to be averaged is consecutive, and each group is directly to the left of the merged cell where I want the average to appear. Does anyone have some insight on how I could better format my code to achieve this? Any ideas are appreciated, thanks.

The reason the formula is entering 'as is' is because you'd need to concatenate it into the string.

For i = 0 To range_num
    ActiveCell.Formula = "=AVERAGE(" & ranges(i) & ")"
Next i

If I have interpreted correctly, you are looking for a code snippet that will loop through a range of cells and set the formula based on the literal string found in another cell. Try the following:

sub SetCellFormulas()

dim sWS as worksheet
dim aCell as range
dim aRange as range
dim Lrow as long

set sws = thisworkbook.sheets("yourworksheetname")

'*** Locate last cell with values in column G
lrow = sws.Range("G11").end(xldown).row

'*** Set range to loop through
set arange = sws.Range("G11:G" & Lrow)
for each acell in arange
  '*** set formula of cell 1 to the left of G to the concatenated formula
  aCell.offset(0,1).formula = "=AVERAGE(" & acell.value & ")"
next acell

end sub

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