【发布时间】:2023-03-08 00:30:01
【问题描述】:
我想在 Excel 工作表上执行一些计算,该工作表的数据集组织如下。
A 列 --> 日期
B 列 --> 小时
C 列到 lastColumn --> 数据
其中一列的名称为“强度”。我想在最后添加一列,它将在小时为“00:00”的行中托管从 00:00 到 23:00 的“强度”值的总和,另一列将为我提供值“05:00”行减去“22:00”行的值。这是我的尝试:
Sub intensity_computations()
Dim k, l, intensity_column As Integer
Dim lastCol, lastRow As Long
Dim rng, start As Range
'I define the variables of the number of the last column and the last row:
lastCol = Cells(1, 1).End(xlToRight).Column
lastRow = Cells(1, 1).End(xlDown).Row
'I find the column number that corresponds to the column "intensity"
For k = lastCol To 1 Step -1
If Not Cells(1, k).Find("intensity") Is Nothing Then
intensity_column = k
End If
Next k
'I create the column with the summed hourly values written at the the rows with hour "00:00:00"
For l = 2 To lastRow
If Cells(l, 2).Value = "00:00:00" Then
start_cell = Cells(l, intensity_column)
rng = Range(start_cell, start_cell.Offset(23, 0))
Cells(l, lastCol + 1) = Application.Sum(rng)
End If
Next l
'I create the column with the subtracted value of hour "22:00" from the value of hour "05:00", which should be written at row with hour "00:00"
For l = 2 To lastRow
If Cells(l, 2).Value = "00:00:00" Then
Cells(l, lastCol + 2).Value = Cells(l, lastCol + 2).Offset(5, -2) - Cells(l, lastCol + 2).Offset(22, -2)
End If
Next l
End Sub
不幸的是,我收到诸如“需要对象”或“不匹配”之类的错误,这取决于第一个 For 循环是放在第二个 For 循环之前还是之后。
有谁能帮忙解决这个问题吗?
【问题讨论】:
-
(1)你不需要第一个循环,
Find可以seach整个范围(2)你在分配对象变量时需要SetSet rng = ...(3)你没有声明start_cell(4) 你不能把第一个循环放在第二个之后,因为你在第一个循环中定义了intensity_column(5) 声明变量时你应该列出每个类型Dim rng as Range, start As Range等等。 -
(6) 第三个循环可以与第二个循环结合起来 (7) 单元格中是否包含文本“00:00:00”或者它们是否为时间格式的数字?
-
我会仔细看看你的建议。至于(7):时间列包含格式为时间而不是文本的值。在 Excel 表中,我可以将 if 语句设置为 if(hour("cell address")=0, ......, ""),但 VBA 不会接受。
-
Myabe 只是
If Cells(l, 2).Value = 0? -
当我调试时,错误是指包含偏移量的 For-loops 和 If-blocks 的表达式。例如。
Cells(l, lastCol + 2).Value = Cells(l, lastCol + 2).Offset(5, -2)工作正常,但Cells(l, lastCol + 2).Value = Cells(l, lastCol + 2).Offset(5, -2) - Cells(l, lastCol + 2).Offset(22, -2)不行。