Page 1 of 1

ตั้งเวลาทำงาน

Posted: Tue May 28, 2013 1:39 am
by P1649

Code: Select all

Sub Counter()

    If Now > Date + TimeValue("10:00:00") Then
        Application.OnTime Date + TimeValue("10:00:00"), "Counter", , True
        Else
        xxx Wait xxx
    End If
    
    If Now > Date + TimeValue("17:00:00") Then
        Application.OnTime Date + TimeValue("17:00:00"), "Counter", , False
        CurrBook.Close
        Exit Sub
    End If
      
    Application.OnTime Now + TimeValue("00:00:10"), "Counter"
    'nTime = Now + TimeValue("00:00:10")
    'Application.OnTime nTime, "Counter"
    
    Call Sound

End Sub
ต้องการตั้งเงื่อนไขให้ทำงานเมื่อเวลา 10.00 และปิดเวลา 17.00
ติดปัญหา คือ เขียนด้วยเงื่อนไขอย่างไรให้รอ เมื่อเวลานั้นน้อยกว่า 10.00

Re: ตั้งเวลาทำงาน

Posted: Tue May 28, 2013 7:49 am
by snasui
:D ลองดู Code ตามด้านล่างครับ

Code: Select all

Dim xxx As Date

Sub Counter()
    If Now < Date + TimeValue("10:00:00") Then
        xxx = Date + TimeValue("10:00:00") - Now
    End If
    If Now > Date + TimeValue("10:00:00") Then
        Application.OnTime Date + TimeValue("10:00:00"), "Counter", , True
        Else
        Application.Wait xxx
    End If   
    'Other code
End Sub

Re: ตั้งเวลาทำงาน

Posted: Tue May 28, 2013 10:21 pm
by P1649
จาการทดลองมีปัญหา 2 ข้อ ขอรบกวนอาจารย์แนะนำด้วยครับ

1). Nwait ค้าง ไม่ทำงานตามเวลาที่ Non กำหนด
2). ปิดไฟล์โดยไม่ถาม save ไม่ทำงาน

Re: ตั้งเวลาทำงาน

Posted: Wed May 29, 2013 8:03 am
by snasui
:D ดูตัวอย่างการปรับ Code ตามด้านล่างครับ

Code: Select all

Public Ntime As Date, Nwait As Date
'Public Non As Date, Noff As Date
'Public CurrBook As Workbook, CheckFile As Boolean

Sub Counter()
    Dim Non As Date, Noff As Date
    Dim CurrBook As Workbook, CheckFile As Boolean
    Set CurrBook = ThisWorkbook
    
    Ntime = Now + TimeValue("00:00:01")
    Non = Date + TimeValue("08:00:00")
    Noff = Date + TimeValue("08:00:10")

    If Now < Non Then
        Nwait = Non - Now
        Application.Wait Now + Nwait
    End If

    If Now > Noff Then
        On Error Resume Next
        Application.OnTime Ntime, "Counter", , False
        CurrBook.Save
        CurrBook.Close
        Exit Sub
    End If
    
    Call Sound
    Call UseSpeech
    Call Sort_Level
    Call C_Copy
    Call Col_Scale
    
    Application.OnTime Ntime, "Counter", , True
    
End Sub

Re: ตั้งเวลาทำงาน

Posted: Wed May 29, 2013 9:16 am
by P1649
ทำงานได้สมบูรณ์ดี ขอบคุณมากครับ