我在Excel 2007中尝试使用下面的代码并生成运行时错误1004.我尝试了不同的方法来解决但不能。需要帮助解决错误,因为我的每个第一个工作表都被命名为不同。
{{1}}
答案 0 :(得分:1)
您需要将shtName
变量的值插入公式中,而不是变量名本身:
Dim shtName As String
shtName = ActiveWorkbook.Worksheets(1).Name
Worksheets(2).Range("F2").Formula = "=AVERAGEIFS('" & shtName & "'!E:E,'" & shtName & "'!A:A,"">="" & A2,'" & shtName & "'!A:A,""<"" & B2)"
(并且通常最好将工作表名称换成单引号,以避免在名称包含空格等时出现问题。)
答案 1 :(得分:0)
您应该将变量放在&#34;&#34;之外,从而将变量从字符串中分离出来。标记。
所以它应该是
Dim shtName As String
shtName = ActiveWorkbook.Worksheets(1).Name
Worksheets(2).Range("F2").Formula = "=AVERAGEIFS(" & shtName & "!E:E," & shtName & "!A:A,"">="" & A2," & shtName & "!A:A,""<"" & B2)"