我有几列不连续数据,每列包含一些需要总结的继续阅读。因此需要在不同范围进行求和。仅当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
答案 0 :(得分: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