简体   繁体   English

写一个动态求和公式 vba 取另一张纸的范围

[英]Write a dynamic sum formula vba that takes range from another sheet

1

I am trying to calculate sum in cell "I13" of sheet2 with inputs based on the dynamic range.我正在尝试使用基于动态范围的输入来计算 sheet2 的单元格“I13”中的总和。

Formula公式

range("I13").formula= "=sum('sheet1'!A1:A3)" 

works but the range can be dynamic.有效,但范围可以是动态的。 For this I have used lr to identify the last row in the range为此,我使用 lr 来识别范围内的最后一行

lr=cells(rows.count,1).end(xlup).row

Now, I want to modify the above formula such that in place of A3, it takes last cell.现在,我想修改上面的公式,以便代替 A3,它采用最后一个单元格。 ie A&lr即A&lr

Have tried using range("I13").formula= "=sum('sheet1':A1:A"&lr)" , but it results in error已尝试使用range("I13").formula= "=sum('sheet1':A1:A"&lr)" ,但会导致错误

Sub MMM()
Windows("Template.xlsx").activate
sheets("sheet1").select
range("a1").select

lr=cells(rows.count,1).end(xlup).row

sheets("sheet2").select

'this code works. But want dynamic range
'range("I13").formula =  "= SUM('sheet1'!A1:A3)"

range("I13").formula =  "= sum('sheet1'!A1:A&lr)"

End Sub

Try to combine the strings for the formula:尝试组合公式的字符串:

range("I13").formula =  "= sum('sheet1'!A1:A" & CStr(lr) & ")"

you can try to define the variable:您可以尝试定义变量:

Option Explicit ' It should be used when you define variable
   Sub MMM()
   Dim lr as Range ' Define variable
        
     Windows("Template.xlsx").activate
     sheets("sheet1").select
     range("a1").select
        
     lr=cells(rows.count,1).end(xlup).row
        
     sheets("sheet2").select
                       
        range("I13").formula =  "= sum('sheet1'!A1:A&lr)"    
   End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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