3D SumIf使用List循环所有工作表最终修复所需

时间:2016-05-20 12:05:39

标签: excel vba excel-vba

我有以下内容列出了cell AI1中工作表摘要中的所有工作表名称,然后删除了前三名,从AI4选择到底部并命名范围“发票“

我正在尝试使用它来对所有工作表执行sumif公式。它可以手动将其粘贴到单元格中 但是在VBA中,来自'"&Invoices&"'!$A$2006:$A$3005"),$A3,INDIRECT("'"&Invoices&"'!B$2006:B$3005")))"

之后它正在将其作为评论(绿色)

阅读
For i = 1 To Sheets.Count
    Sheets("Summary").Range("AI1")(i, 1).Value = Sheets(i).Name
Next i

Sheets("Summary").Select
Sheets("Summary").Range("AI1:AI3").Clear
Sheets("Summary").Activate
Sheets("summary").Range(ActiveSheet.Range("AI4"),
ActiveSheet.Range("AI4").End(xlDown)).Select
Selection.Name = "Invoices"
Sheets("summary").Range("B3").Formula =    "=SUMPRODUCT(SUMIF(INDIRECT("'"&Invoices&"'!$A$2006:$A$3005"),$A3,INDIRECT("'"&Invoices&"'!B$2006:B$3005")))"

2 个答案:

答案 0 :(得分:1)

扩展我的评论: VBA认为“是字符串的结尾,所以如果你想让它实际上被视为一个字符,你需要将它作为”“转义。” 你的代码应该是:

Sheets("summary").Range("B3").Formula =     "=SUMPRODUCT(SUMIF(INDIRECT(""'""&Invoices&""'!$A$2006:$A$3005""),$A3,INDIRECT(""'""&Invoices&""'!B$2006:B$3005"")))"

当有很多字符时,检查这个的简单方法是在即时窗口中写入它。我把

? "=SUMPRODUCT(SUMIF(INDIRECT(""'""&Invoices&""'!$A$2006:$A$3005""),$A3,INDIRECT(""'""&Invoices&""'!B$2006:B$3005"")))"

确认。

答案 1 :(得分:0)

谢谢,  所以对于其他需要这个的人来说,就是这样做的完整方式

 *****'list all the sheet names in cell AI1 of the sheet summary*****
For i = 1 To Sheets.Count
Sheets("Summary").Range("AI1")(i, 1).Value = Sheets(i).Name
Next i
***'clear the first 3 entries in AI as i didnt need the first three sheet names***
Sheets("Summary").Select
Sheets("Summary").Range("AI1:AI3").Clear
***'select the first sheet name, which is in AI4 as we cleard the first 3 to the last used cell, e.g Ctrl.Shift.down*** 
Sheets("Summary").Activate
Sheets("summary").Range(ActiveSheet.Range("AI4"),    ActiveSheet.Range("AI4").End(xlDown)).Select
***' Name the range invoices***
Selection.Name = "Invoices"
' ***Formula to do a sumIf looping all the shets in the named range Invoices***
Sheets("summary").Range("B3").Formula = "=SUMPRODUCT(SUMIF(INDIRECT(""'""&Invoices&""'!$A$2006:$A$3005""),$A3,INDIRECT(""'""&Invoices&""'!B$2006:B$3005"")))"