我的数据形式为1 1 1(1月1日1小时)至12 31 24(12月31日最后一小时)。我正在尝试每天使用(与每天相关的24小时),然后找出一年中所有日子的最大消费量。尝试使用VBA在Excel中制作宏
1 1 1 0.011
其中A列为月,B列为日,C列为小时,D列为使用
编辑:那么,如果可能的话,指出哪个日期有用?
答案 0 :(得分:0)
这是我的解决方案:这假设您的第一行是标题,数据从第2行开始。
Sub getUsage()
Dim lim As Integer
Dim count As Integer
Dim total As Double
Dim rVal As range
total = 0
Final = 0
lim = Sheet1.range("B2", Sheet1.range("B2").End(xlDown)).Rows.count
For count = 0 To lim
total = total + Sheet1.range("B2").Offset(count, 2).Value
If Sheet1.range("B2").Offset(count, 1) = 1 Then
If total > Final Then
Final = total
Set rVal = Sheet1.range("B2").Offset(count, 0)
End If
total = 0
End If
Next
MsgBox ("The date with the largest usage is: " & rVal.Offset(0, -1) & ", " & rVal.Offset(0, 0) & ", " & rVal.Offset(0, 1))
End Sub
答案 1 :(得分:0)
此用户定义的功能¹处理内存中的数据块,并返回每日最大使用量及其发生的日期。
Function fcnDatedMax(rng As Range, Optional yr As Integer = 2015)
Dim u As Long, vUSEs As Variant, dbl As Double
With rng
vUSEs = .Resize(.Rows.Count + 1, .Columns.Count).Value2
For u = 1 To 4
vUSEs(UBound(vUSEs, 1), u) = vUSEs(LBound(vUSEs, 1), u)
Next u
dbl = vUSEs(UBound(vUSEs, 1), UBound(vUSEs, 2))
End With
For u = LBound(vUSEs, 1) + 1 To UBound(vUSEs, 1) - 1
If vUSEs(u, 2) <> vUSEs(u - 1, 2) Then
If dbl > vUSEs(UBound(vUSEs, 1), UBound(vUSEs, 2)) Then
vUSEs(UBound(vUSEs, 1), 1) = vUSEs(u - 1, 1)
vUSEs(UBound(vUSEs, 1), 2) = vUSEs(u - 1, 2)
vUSEs(UBound(vUSEs, 1), 3) = vUSEs(u - 1, 3)
vUSEs(UBound(vUSEs, 1), 4) = dbl
End If
dbl = vUSEs(u, UBound(vUSEs, 2))
Else
dbl = dbl + vUSEs(u, UBound(vUSEs, 2))
End If
Next u
fcnDatedMax = Format(DateSerial(yr, vUSEs(UBound(vUSEs, 1), 1), vUSEs(UBound(vUSEs, 1), 2)), "dd-mmm-yyyy ") & _
vUSEs(UBound(vUSEs, 1), UBound(vUSEs, 2))
Erase vUSEs
End Function
在G145和H145中,
=MAX(E:E)
=fcnDatedMax(A2:D2161)
这贯穿一年的第一季度,并返回正确的每日最高值以及发生的日期。
¹用户定义函数(又名UDF)被放入标准模块代码表中。点击 Alt + F11 ,当VBE打开时,立即使用下拉菜单插入►模块( Alt + 我,中号)。将功能代码粘贴到标题为 Book1 - Module1(Code)的新模块代码表中。点击 Alt + Q 返回工作表。