LƯU FILE bị trùng tên với file đã có trong cùng 1 folder

Chia sẻ bởi:hands
★★★★★
Quảng cáo

Thưa anh chị

Em đang gặp phải vấn đề, e đã lưu đc và đặt tên file định dạng xlsx vào trong 1 folder cùng với file viết code
Nhưng e đang có vấn đề là, nếu em lưu file đó 1 lần nữa với tên và định dạng giống như file đã lưu thì nó đè lên file cũ
E muốn làm thế nào để nếu em tiếp tục lưu thì file đó sẽ hiển thị với tên và kí tự khác 1 chút, giả sử như A.xlsx thì sẽ có A(1).xlsx
Kính mong anh chị nào biết, or đã gặp trường hợp này thì chỉ dạy cho em

Private Sub CommandButton1_Click()
Dim path As String
Dim item As Variant
item = Range("D12")
fname = item & " " & Format(Date, "dd-mm-yyyy")
Application.DisplayAlerts = False
    Sheets(1).Copy
    ActiveSheet.Shapes("CommandButton1").Delete
    With ActiveWorkbook
        .SaveAs ThisWorkbook.path & "/" & item & " " & Format(Date, "dd-mm-yyyy") & ".xlsx"
        .Close
    End With
Application.DisplayAlerts = True
End Sub

tham khảo bạn ơi :

Private Sub CommandButton1_Click()
    Dim path As String
    Dim item As Variant
    Dim suffix As Integer 'declare a variable to hold the suffix number
    suffix = 1 'initialize the suffix to 1

item = Range("D12")
    fname = item & " " & Format(Date, "dd-mm-yyyy")

'loop until the file name is unique
    Do While Len(Dir(ThisWorkbook.path & "/" & fname & ".xlsx")) > 0
        'add the suffix to the file name
        fname = item & " " & Format(Date, "dd-mm-yyyy") & " " & suffix
        suffix = suffix + 1 'increment the suffix
    Loop

Application.DisplayAlerts = False
    Sheets(1).Copy
    ActiveSheet.Shapes("CommandButton1").Delete
    With ActiveWorkbook
        .SaveAs ThisWorkbook.path & "/" & fname & ".xlsx"
        .Close
    End With
    Application.DisplayAlerts = True
End Sub

www.giaiphapexcel.com/diendan/threads/l%C6%AFu-file-b%E1%BB%8B-tr%C3%B9ng-t%C3%AAn-v%E1%BB%9Bi-file-%C4%91%C3%A3-c%C3%B3-trong-c%C3%B9ng-1-folder.163693/post-1091957

Mình làm thế này cho gọn vậy.

.SaveAs ThisWorkbook.path & "/" & item & " " & Format(Now, "dd-mm-yyyy_hh_nn_ss") & ".xlsx"

www.giaiphapexcel.com/diendan/threads/l%C6%AFu-file-b%E1%BB%8B-tr%C3%B9ng-t%C3%AAn-v%E1%BB%9Bi-file-%C4%91%C3%A3-c%C3%B3-trong-c%C3%B9ng-1-folder.163693/post-1091958

Ứng dụng AI và Chat GPT trong Quản trị nhân sự
Khóa học SprinGO phù hợp

Ứng dụng AI và Chat GPT trong Quản trị nhân sự

Học xong khóa này, học viên có thể: Hiểu đúng bản chất AI, các nhóm AI phổ biến và cách AI “hoạt động” ở...

Xem khóa học
★★★★★ 5 ★ 1 👤 0 ▥ 0
Quảng cáo

Bạn nên đọc

Leave a Reply

Your email address will not be published. Required fields are marked *

Quảng cáo

Cũ vẫn chất

Xem thêm