Run code if Username match And current time is between 2 sets of time.

countryfan_nt

Well-known Member
Joined
May 19, 2004
Messages
765
Hello friends, hope all is well!

Can you please help me with the code below:

I want the code to close the workbook if:
1. UserName is NOT Johnny Case AND
2. Between times 17:45 and 17:59 OR
3. Between times 07:45 and 07:59

The code is placed below; thank you very much in advance!


Code:
Private Sub Workbook_Open()

' ===== Environ User Name validation ====
Dim nm As String
nm = UCase(Application.UserName)
time = Now

If nm = "Johnny Cash" or If Time => TimeValue("17:45:00") And Time <= TimeValue("17:59:00") or If Time => TimeValue("07:45:00") And Time <= TimeValue("07:59:00") Then   
Sheets("MAIN").Range("N1").Value = "Yes" Then

  Sheets("MAIN").Select
  Range("A1").Select

Application.Wait (Now + TimeValue("0:00:05"))

Application.DisplayAlerts = False
ActiveWorkbook.Close SaveChanges:=False

         Else

  Sheets("Sheet1").Select
  Range("A1").Select

         End If
End Sub
 

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December
NOW give both date and time If I put NOW in a variable it is

4/22/2019 1:22:55 PM

Try using TIME

You should change your variable name since TIME is used by VBA.
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,886
Messages
6,175,191
Members
452,616
Latest member
intern444

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