2015-07-04 76 views
1

從當月的20日到下個月的19日創建表。爲什麼不會運行下面的代碼?從本月的特定日期到下個月的特定日期創建Excel VBA表

Dim sDate As Date, nDate As Date 

sDate = DateSerial(Year(Date), Month(Date), 20) 

nDate = DateSerial(Year(Date), Month(Date) + 1, 19) 

For k = sDate To nDate  'DaysInMonth 
     'copy template sheet 
     wbkCur.Worksheets("Template").Copy After:=Sheets(wbkCur.Worksheets.Count) 
     Select Case k 
      Case 1, 21, 31 
       TabName = "st" 
      Case 2, 22 
       TabName = "nd" 
      Case 3, 23 
       TabName = "rd" 
      Case Else 
       TabName = "th" 
     End Select 
     'rename to Day of Month 
     ActiveSheet.Name = ShortName & " " & k & TabName 
next k 
+0

你試過跟蹤錯誤?你得到了什麼? –

回答

2

試試這個:

Option Explicit 

Sub dural() 
    Dim wbkCur As Workbook, ws As Worksheet 
    Dim sDate As Date, nDate As Date 
    Dim i As Integer 
    Dim k As Date 
    Dim TabName As String, ShortName As String 

    sDate = DateSerial(Year(Date), Month(Date), 20) 
    nDate = DateSerial(Year(Date), Month(Date) + 1, 19) 

    Set wbkCur = ThisWorkbook 

    For k = sDate To nDate 
     i = Day(k) 

     wbkCur.Worksheets("Template").Visible = xlSheetVisible 
     wbkCur.Worksheets("Template").Copy After:=wbkCur.Sheets(wbkCur.Worksheets.Count) 
     Set ws = ActiveSheet 

     Select Case i 
      Case 1, 21, 31: TabName = i & "st" 
      Case 2, 22: TabName = i & "nd" 
      Case 3, 23: TabName = i & "rd" 
      Case Else: TabName = i & "th" 
     End Select 

     '~~> 23rd_1_2015. The earlier replace was creating 7_20_2015th 
     TabName = ShortName & " " & TabName & "_" & Month(k) & "_" & Year(k) 
     '~~> For m_dd(th)_2015, uncomment the below 
     'TabName = ShortName & " " & Month(k) & "_" & TabName & "_" & Year(k) 

     '~~> Delete any sheet with the existing name else 
     '~~> Renaming sheet to an existing name will give an error 
     On Error Resume Next 
     Application.DisplayAlerts = False 
     wbkCur.Sheets(TabName).Delete 
     Application.DisplayAlerts = True 
     On Error GoTo 0 

     ws.Name = TabName 
    Next k 
End Sub 
+0

感謝加里的學生,但我仍然在for循環 – roninn75

+0

@ roninn75上出現「overflow」錯誤,哪行? –

+0

@ roninn75請注意我在某些行上使用** i **代替** k **! –

相關問題