簡體   English   中英

VBA - 如果最大日期在當前月份,如何識別列中的最大日期並使用當前年份和月份保存文件

[英]VBA - How to identify max date in a column and save file with current year and month if the max date is in the current month

這是我試圖解決的兩部分問題。 首先,我想確定列中的最大日期。 如果最大日期在當前月份,那么我想使用當前年份和月份(文件名 YYYYMM)以當前格式保存文件。 如果日期小於當前月份,我想保存當前年份和上個月的文件。

這是我開始用於識別最大日期的代碼,但我的 MsgBox 顯示時間而不是日期,所以我無法確認它是否真的有效。

Dim Max_date As Date
xl.Sheets("Data").Visible = True
xl.Sheets("Data").Select
xl.Range("I:I").Select
Max_date = Application.WorksheetFunction.Max(xl.Range("I:I"))
MsgBox Max_date

請花時間檢查代碼並配置您需要的所有內容。 祝你好運

'This es the configurable part
Sub Export()
    Dim filePath As String, fileName As String
    filePath = OpenFileExplorer(msoFileDialogFolderPicker) '"" 'define your save path         or use -->'OpenFileExplorer(msoFileDialogFolderPicker)
    fileName = "eg. 09_03_2021" 'here you code max, remember dont use slash
    Copy_Save_Worksheet_As_Workbook "your Sheet to save", fileName, filePath
End Sub

'Starting a procedure to save a worksheet as new workbook
Public Sub Copy_Save_Worksheet_As_Workbook(SheetNameToCopy_ As String, saveAs__ As     String, path_ As String)
    Application.ScreenUpdating = False
    Dim wkb As Workbook
    'Check this line too
    Const fileExtencion = ".xlsx"
    'this is to check if already book open with same name
    For Each wkb In Workbooks
        If wkb.Name = saveAs__ & fileExtencion Then
            Workbooks(wkb.Name).Close False
        End If
    Next
   
    Dim finalPath As String
    finalPath = path_ & "\" & saveAs__
    ThisWorkbook.Sheets(SheetNameToCopy_).Select
    ActiveSheet.Copy
    ActiveSheet.SaveAs fileName:=finalPath & ".xlsx"
    Application.ScreenUpdating = True
 End Sub

Public Function OpenFileExplorer(t_ As MsoFileDialogType) As String
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(t_)
   With fd
      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Where to save"

      ' Clear out the current filters, and add our own.
      .Filters.Clear
     If t_ = msoFileDialogFilePicker Then
          .Filters.Add "All Files", "*.*"
     End If
     If .Show = True Then
         OpenFileExplorer = .SelectedItems(1)
     Else
        OpenFileExplorer = ""
     End If
   End With
End Function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM