excel - Running VBA code in alternate sheet triggers wrong results - despite referencing? -
the below code seeks pull value cell in the 'input' sheet, , display in 'output' sheet. shows difference between last value recorded , expresses figure percentage.
when run code output sheet active works. however, when run output sheet doesn't. instead, displays value wish copy in column f in input sheet , displays difference , percentage difference in wrong cells in output sheet.
it looks correctly referenced me, isn't. thoughts on how correct?
i appreciate code tidier - i'm new this.
sub button1_click() dim lastrow long dim recentrow long sheets("output") lastrow = .cells(.rows.count, "f").end(xlup).row recentrow = .cells(.rows.count, "f").end(xlup).offset(1, 0).row range("f" & lastrow).select activecell.offset(1, 0).formula = "=input!b4" activecell.offset(1, 0).copy activecell.offset(1, 0).pastespecial (xlvalues) end activecell.offset(0, 1).formula = "=(f" & recentrow & "-f" & lastrow & ")" activecell.offset(0, 2).formula = "=((f" & recentrow & "/f" & lastrow & ")-1)" end sub
thanks.
the below code should fix issue - it's because range("f" & lastrow).select did not have period before range.
sub button1_click() dim lastrow long dim recentrow long sheets("output") lastrow = .cells(.rows.count, "f").end(xlup).row recentrow = .cells(.rows.count, "f").end(xlup).offset(1, 0).row .range("f" & lastrow) .offset(1, 0).formula = "=input!b4" .offset(1, 0).copy .offset(1, 0).pastespecial (xlvalues) .offset(0, 1).formula = "=(f" & recentrow & "-f" & lastrow & ")" .offset(0, 2).formula = "=((f" & recentrow & "/f" & lastrow & ")-1)" end end end sub
furthermore, can gain bit more efficiency in code below:
sub button1_click() dim lastrow long thisworkbook.sheets("output") 'allow code work if in workbook. lastrow = .cells(.rows.count, "f").end(xlup).row .range("f" & lastrow) .offset(1, 0).value2 = thisworkbook.sheets("input").range("b4").value2 .offset(0, 1).formula = "=(f" & lastrow + 1 & "-f" & lastrow & ")" .offset(0, 2).formula = "=((f" & lastrow + 1 & "/f" & lastrow & ")-1)" end end end sub
Comments
Post a Comment