首页 文章

选择定义为日期的工作表

提问于
浏览
0

我有一个工作簿,其中多个工作表根据日期命名(格式为MMDDD) . 此宏应循环遍历所有日期表(如01OCT,02OCT,.... 30OCT)选择范围并将其复制到新工作表中 .

选择单元格,复制它们等等并不是真正的问题,这是完美的 . 但是我确定了定义工作表名称的问题 . 我希望用户在开始时使用InputBox定义月份和月份和月份的天数 .

因此,如果用户选择month =“FEB”和DaysMonth = 28,我希望宏来循环使用名为01FEB,02FEB,03FEB,.... 28FEB的表格 .

Sub Merge_whole_month()

    Application.ScreenUpdating = False

        Dim month As String

            month = InputBox(Prompt:="Please enter month in format MMM", _
                  Title:="Month")

        Dim DaysMonth As Long

            DaysMonth = InputBox(Prompt:="Please enter number of days in month", _
                  Title:="Days")

    'create new sheet for results
        Sheets.Add.Name = "Merge"

    'loop
    For i = 1 To DaysMonth
        i = Format(i, "##")

        Sheets(i & month).Activate 'here is the problem

    'select cell G3, then all "non-empty" cells to the right and down and COPY

        Range(Range("G3", Range("G3").End(xlToRight)), Range("G3", Range("G3").End(xlToRight)).End(xlDown)).Select
        Selection.Copy

        Sheets("Merge").Activate 'activate sheet where cells needs to be copied

    'find last cell in 2nd row in sheet
        lastCol = Cells(2, Columns.Count).End(xlToLeft).Column
        lastCol = lastCol + 1

            Cells(1, lastCol) = i & month   'log date and month in cell above

                Cells(2, lastCol).Select
                ActiveSheet.Paste               'Paste

    Next i

    Application.ScreenUpdating = True

    End Sub

非常感谢您的帮助!

1 回答

  • 0

    问题在于 i = Format(i, "##") 不会使 i 小于10显示为 01 等 . 为了解决这个问题,我会这样做:

    Dim sDate As String
    sDate = CStr(i)
    If Len(sDate) < 2 Then
        sDate = "0" & sDate
    End If
    

    Sheets(i & month).Activate 之前将该代码放在for循环中并删除 i = Format(i, "##") .

    编辑:

    对我来说似乎使用 Format(i, "0#") 给出了你正在寻找的字符串 . 但是,您仍然需要将其分配给String变量或将 Sheets(i & month).Activate 更改为 Sheets(Format(i, "0#") & month).Activate .

    HereFormat() 函数的文档 . 我建议阅读它 .

相关问题