What's a more effective way to write this code?

Macro_Nerd99

Board Regular
Joined
Nov 13, 2021
Messages
61
Office Version
  1. 365
What's a more effective way to write this code so I don't have to insert text into cells and then delete it?
Also, how would I display the total hours worked in 40:00:00 format, instead of a 40.0 decimal format?
Any other advice/feedback is appreciated.


VBA Code:
Public Sub Calculate_Hours()
Dim StartTime as date
dim EndTime as date
dim i as integer
dim lr as long
dim fr as long
dim total_hours as long


With thisworkbook.activesheet.autofilter.Range
fr = Range("B" & .offset(1,0).specialcells(xlcelltypevisible)(1).row).row
lr = cells(Rows.Count,"C").end(xlUp).row
end with

for i = fr to lr
StartTime = ws.range("B" & i).value
EndTime = ws.Range("C".value
ws.range("H" & i).value = datediff("n", starttime, EndTime)/60
Next i

Total_hours = application.worksheetfunction.sum(Range("H" & fr & ":H" & lr))
Filter_Form.hours_tb.text= Total_hours
Range("H" & fr & ":h" & lr).clearcontents

End Sub
 

Excel Facts

When did Power Query debut in Excel?
Although it was an add-in in Excel 2010 & Excel 2013, Power Query became a part of Excel in 2016, in Data, Get & Transform Data.
change your code like this:
VBA Code:
total_hours = 0
For i = fr To lr
starttime = ws.Range("B" & i).Value
EndTime = ws.Range("C".value
total_hours = total_hours + DateDiff("n", starttime, EndTime) / 60
Next i

Filter_Form.hours_tb.Text = total_hours
 
Upvote 0
Hi.
The code you show never worked because in:
VBA Code:
ws.Range("C".value

it is missing the row and a parenthesis.
___________________________

On the other hand, it is not clear if you want to apply this operation to all the rows of the range or only to the visible cells of the filtered range.
 
Upvote 0
What filter are you applying before you run your code?
 
Upvote 0

Forum statistics

Threads
1,215,087
Messages
6,123,050
Members
449,092
Latest member
ikke

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top