2016-06-24 132 views
1

我收到了下面的代碼錯誤箱:「範圍類的小計方法失敗」。我該如何解決這個問題,以及如何重寫代碼,以便它可以容納不斷變化的小數列?VBA Excel小計錯誤

Range("A1").Select 
Selection.Subtotal GroupBy:=3, Function:=xlSum, TotalList:=Array(14, 15, 16 _ 
    , 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, _ 
    43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63), Replace:= _ 
    True, PageBreaks:=False, SummaryBelowData:=True 
+0

這是否幫助:http://stackoverflow.com/questions/23276881/run-time-error-1004-subtotal -method-of-range-class-failed – Vityata

+1

*我如何重寫代碼,以便它可以適應不斷變化的列數* - 您需要遍歷每列,並將列號加載到數組變量中,並且將其傳遞給'TotalList'參數。 –

回答

0

如果這是一個數組,你可以建立像下面

Dim ArrayNumbers() As String 
Dim CounterArray As Long 
For CounterArray = 1 To 49 
ReDim Preserve ArrayNumbers(CounterArray) 
'I'm not quite sure if parsing empty elements in the 'Total List' arg would give error, so instead we are going to start in the element 1 of the array doing the value 14 for it and so on. 
ArrayNumbers(CounterArray) = IIf(CounterArray <> 1, "," & CounterArray+14, CounterArray+14) 'this is to avoid the comma in the first value just for all the other ones 
Next CounterArray 
Range("A1").Select 
Selection.Subtotal GroupBy:=3, Function:=xlSum, TotalList:=ArrayNumbers, Replace:= _ 
    True, PageBreaks:=False, SummaryBelowData:=True 
+0

「Selection.Subtotal」行的「運行時錯誤1004範圍類的小計方法失敗」。如果我想自己輸入列號,也可以將'49'更改爲'i'嗎? – lindqmx1

+0

是的,你可以用你的代碼來達到什麼目的? – Sgdva

+0

每當列C的數據發生變化時,我需要爲可變數量的列添加行小計。我知道如何在counterArray中添加一個變量,但是原因是代碼會得到上述錯誤。 – lindqmx1