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

countryfan_nt

Well-known Member
Joined
May 19, 2004
Messages
758
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

What did Pito Salas invent?
Pito Salas, working for Lotus, popularized what would become to be pivot tables. It was released as Lotus Improv in 1989.
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,213,506
Messages
6,114,024
Members
448,543
Latest member
MartinLarkin

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