我正在尝试在一张工作表中创建一个函数,该函数汇总另一张工作表上的信息,由于我将使用不同的数据集多次运行该函数,因此我需要该函数具有灵活性。我尝试为此使用单元格引用,如下所示:Range("AP3") = WorksheetFunction.Sum(Worksheets("Results").Range(Cells(3, AEPC), Cells(LR, AEPC)))
但失败了。
AEPc 是列号,LR 是最后一行。如果需要,我可以提供完整的脚本。
令人恼火的是 - 它确实识别了工作表,当我尝试使用最后一行代码选择行时,它可以工作。出于某种原因,当我将其放入 Sum 函数时,它不喜欢它。
任何帮助都将非常感激!
Sub Functions()
Dim desiredShetName As Worksheet
Dim NewName As Worksheet
ActiveWorkbook.Sheets("Counts_Tables_Macro").Activate
Set desiredSheetName = ThisWorkbook.Worksheets("Results")
'Finding the AEP box in Counts Tab to run calculations
'AEPNC = WorksheetFunction.Match(AEP, Worksheets(NewName).Rows(16), 0)
'Finding the corresponding AEP box in Results Tab
AEPC = WorksheetFunction.Match("5YR", Worksheets("Results").Rows(2), 0)
'Finding the residential property Column in Results Tab
PropNumC = WorksheetFunction.Match(Worksheets("DATA IN").Range("D2"), Worksheets("Results").Rows(2), 0)
'Finding the 'Class' column in Results Tab ** Requires change if column name changes **
ClassC = WorksheetFunction.Match("Class", Worksheets("Results").Rows(2), 0)
'Getting last row in Results Tab
With Sheets("Results")
LR = .Range("B" & .Rows.Count).End(xlUp).Row
End With
'this is all testing
Range("AP1") = Application.WorksheetFunction.Sum(Range("AA10:AA12"))
Range("AP2") = WorksheetFunction.Sum(Worksheets("Results").Range("DU3:DU17079"))
Set Crange = Range(Cells(3, AEPC), Cells(LR, AEPC))
'Range(Cells(3, AEPC), Cells(LR, AEPC)).Select
'Sheets("Results").Select
'Sheets("Results").Range(Cells(3, AEPC), Cells(LR, AEPC)).Select
Range("AP3") = 1
Range("AP3") = WorksheetFunction.Sum(Worksheets("Results").Range(Cells(3, AEPC), Cells(LR, AEPC)))
'Range("AP2") = SumV
'Range("AP2") = Application.WorksheetFunction.Sum(WorkSheets("CBC_PIX_OSMM_MIT6-with 10%C (3)).Range("DU3:DU1700"))
'Range("C18").FormulaR1C1 = "=SUMIF('" & desiredSheetName & "' !R[3]C[ClassC]:R[LR]C[ClassC], '" & NewName & "' !R[17]C[2], '" & NewName & "'!R[3]C[AEPC]:R[LR]C[AEPC])"
End Sub
答案1
您没有声明公式中的单元格的位置。
我没有看过你的所有代码,因为其中有很多无用的东西——注释和不相关的代码行。
此过程希望指出错误:
Sub Test()
Dim LR As Long
LR = 10
Dim AEPC As Long
AEPC = 5
Dim ResultSheet As Worksheet
Set ResultSheet = ThisWorkbook.Worksheets("DATA IN")
'Qualify all range and cell references.
'You should also use the workbook - ThisWorkbook.Worksheets("Results").Range(.....
Dim SumResult As Long
SumResult = WorksheetFunction.Sum(ResultSheet.Range(ResultSheet.Cells(3, AEPC), ResultSheet.Cells(LR, AEPC)))
End Sub
从外观上看,您的 Sum 行应为:
Worksheets("Results").Range("AP3") = WorksheetFunction.Sum(Worksheets("Results").Range(Worksheets("Results").Cells(3, AEPC), Worksheets("Results").Cells(LR, AEPC)))