2017-08-31 59 views
0

我有幾列不連續的數據,每列包含一些需要總結的繼續讀取。因此需要不同範圍的總和。只有當x大於1並且其值定義了範圍的大小(在活動單元格上方選擇的行數)時纔會進行求和。但是「rng1 = .. address」導致了應用程序定義或對象定義的錯誤。我的代碼是不那麼整潔,但我敢肯定,所有的變量保持期望值,請幫助..如何在單元格地址中使用變量裏面的變量

Sub Dynamic_rowsRangeNumbers() 
Dim rng1 As String, rng2 As String 
Dim nrow As Integer 
Dim x, ncol As Integer 

ThisWorkbook.Worksheets("Sheet5").Activate 
For ncol = 2 To 4 
    For nrow = 3 To 28 
    x = Cells(nrow, 216 + ncol).Value 
    rng1 = Cells(nrow - x + 1, ncol).Address *** run-time error 1004 
    rng2 = ActiveCell.Address 

    'If reference cell has value FZ>=1 Then 
    If (Cells(nrow, 216 + ncol).Value >= 1) Then 
    Cells(nrow, 254 + ncol).Formula = "=sum(" & (rng1) & ":" & (rng2) & ")" 
    End If 
    Next nrow 
Next ncol 
End Sub 
+2

x失敗時的值是多少? – SJR

+1

可能沒有鏈接到你的問題,但'Dim rng1,rng2 As String'只會將'rng2'聲明爲'string',而'rng1'將被視爲'variant'類型的變量。你應該寫'Dim rng1 As String,rng2 As String' –

+0

我的直覺是移動你的If(Cells(nrow,216 + ncol).Value> = 1)然後'語句使它直接在'For nrow = 3至28'聲明可能會解決的問題。即使它沒有解決問題,它也應該被移動 - 除了** If塊之外,這兩條語句之間的三條線都不需要。 (但是我想你可以把'x = ...'這一行放在原來的位置,然後在後面有'If x> = 1 Then'。) – YowE3K

回答

0

不能使用在數值計算的非數字值,所以測試值在做之前是數字任何東西:

Sub Dynamic_rowsRangeNumbers() 
    Dim rng1 As String, rng2 As String 
    Dim nrow As Long 
    Dim x As Long, ncol As Long 

    With ThisWorkbook.Worksheets("Sheet5") 
     For ncol = 2 To 4 
      For nrow = 3 To 28 
       If IsNumeric(.Cells(nrow, 216 + ncol).Value) Then 
        x = .Cells(nrow, 216 + ncol).Value 
        'If reference cell has value FZ>=1 Then 
        If x >= 1 Then 
         rng1 = .Cells(nrow - x + 1, ncol).Address 
         'This next line seems wrong - you were never moving ActiveCell 
         'rng2 = ActiveCell.Address 
         'I think you wanted 
         rng2 = .Cells(nrow, ncol).Address 

         .Cells(nrow, 254 + ncol).Formula = "=sum(" & rng1 & ":" & rng2 & ")" 
        End If 
       End If 
      Next nrow 
     Next ncol 
    End With 
End Sub 
+0

謝謝。它正在工作 –