2017-02-01 203 views
0

我正在通過將來自原始文件的數據粘貼到我的模板(稱爲PA Reach)中來自動化一些報告。我點名了一系列「Sumrow」,我需要VBA在粘貼數據後,自動求和上述每個環的數目這裏是我有什麼,我得到錯誤:VBA自動選擇範圍

Workbooks.Open datapath & datafile1 & OutputFileExt 
    Sheets("Rep").Activate 
    ActiveSheet.UsedRange.AutoFilter   

    For i = 1 To terrs_to_generate 
    Workbooks(builder).Sheets("Control").Activate 

    Range("Reportnum") = i 
    currfile = Range("CurrFile").Value 
    currterr = Range("CurrTerr").Value 
    currRep = Range("currRep").Value 
    terrname = Range("terrname").Value 
    DMName = Range("DMName").Value 
    TMStartDate = Range("TMstartdate").Value 

    'open template 
    Workbooks.Open templatepath & templatefile & OutputFileExt 

    Set currtemplatefile = ActiveWorkbook 

    Sheets("Control").Select 
    Sheets("control").Range("terrname") = terrname 
    Sheets("control").Range("repname") = currRep 
    Sheets("control").Range("reportdate") = reportdate 
    Sheets("control").Range("TMstartdate") = TMStartDate 
    Sheets("control").Range("DMName") = DMName 
    Sheets("control").Range("Territory") = currterr 

    Workbooks(datafile1 & OutputFileExt).Activate 
    Selection.AutoFilter field:=1, Criteria1:=currterr 

    Range("A1").Select 
    Range(Selection.Offset(1, 1).End(xlDown), Selection.End(xlToRight)).Copy 
    currtemplatefile.Activate 
    Sheets("PA Reach").Select 
    Range("pasterange").Select 
    Selection.PasteSpecial Paste:=xlPasteValues 

    currtemplatefile.Activate 
    Range("formatrow").Copy 

    Range("pasterange").Select 
    Range(Selection.End(xlToRight), Selection.End(xlDown).Offset(0, 0)).Select 
    Selection.PasteSpecial Paste:=xlPasteFormats 

    'Delete PasteRange 
    Range("pasterange").Select 
    Selection.EntireRow.Delete 

    'Value Range Sheet so no formulas show 
    ActiveSheet.UsedRange.Select 
    Selection.Copy 
    Selection.PasteSpecial Paste:=xlPasteValues 

    Range("A1").Select 



Sheets("control").Delete 
'need to add in sum total 
Range("sumrow1").End(xlDown).Offset(1, 0) = "=Sum(" & Range("sumrow1").Address(True, True) & ")" 



    'save as and close 
    ActiveWorkbook.SaveAs Filename:=(reportpath & currfile & OutputFileExt) 'not working 
+1

你可以清理這些代碼了大量以下[避免選擇/激活](http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros) – Rdster

回答

0

沒有需要SelectRange("sumrow"),然後使用Selection,可以直接修改FormulaRange

嘗試下面的代碼,它會把Sum公式在該行的「sumrow」的底部行下面命名範圍:

Range("sumrow").End(xlDown).Offset(1, 0) = "=Sum(" & Range("sumrow").Address(True, True) & ")" 
+0

這是真棒,它的工作。然而,它是總結橫向,我怎麼能使它和上面的行? – SQUISH

+0

@SQUISH你上面的那一行是什麼意思?你只想總和整個範圍的最後一行? –

+0

我想在sumrow上面直接求和單元格,現在它正在求和整行。有意義嗎? – SQUISH