简体   繁体   English

从本月的特定日期到下个月的特定日期创建Excel VBA工作表

[英]Create Excel VBA sheets from specific day of this month till specific day of next month

I am creating sheets from the 20th of the month till the 19th of the next month. 我将在每月的20号到下个月的19号之间创建表格。 Why wouldn't the following code run? 为什么以下代码不运行?

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

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM