Hướng dẫn record nội dung vào dòng cuối cùng của file khác và tạo mã thể hiện đã lưu

Liên hệ QC
Tôi tuân thủ nội quy khi đăng bài

pham ha 94

Thành viên chính thức
Tham gia
13/12/22
Bài viết
86
Được thích
6
Như tiêu đề em đã viết, mong muốn có file A khi bấm VBA sẽ ghi một số nội dung sang file B
File B và file A sẽ không cùng một thư mục
Có ghi lại thời gian bấm
Nếu dữ liệu đã có thì update, nếu chưa có thì sẽ được ghi và căn cứ theo nội dung trong cột chính
Em cảm ơn cả nhà
 

File đính kèm

  • file dùng vba.xls
    32.5 KB · Đọc: 4
  • file gốc.xls
    22 KB · Đọc: 8
Như tiêu đề em đã viết, mong muốn có file A khi bấm VBA sẽ ghi một số nội dung sang file B
File B và file A sẽ không cùng một thư mục
Có ghi lại thời gian bấm
Nếu dữ liệu đã có thì update, nếu chưa có thì sẽ được ghi và căn cứ theo nội dung trong cột chính
Em cảm ơn cả nhà
Trong file có code rồi đó thôi. chưa đáp ứng được à
 
Upvote 0
Như tiêu đề em đã viết, mong muốn có file A khi bấm VBA sẽ ghi một số nội dung sang file B
File B và file A sẽ không cùng một thư mục
Có ghi lại thời gian bấm
Nếu dữ liệu đã có thì update, nếu chưa có thì sẽ được ghi và căn cứ theo nội dung trong cột chính
Em cảm ơn cả nhà
Bạn tham khảo:
Mã:
Option Explicit

Dim dicOpenBook As New Dictionary

Public Function SheetExists(ByVal book As Workbook, ByVal sheetName As String) As Boolean
    Dim sht As Worksheet
    SheetExists = False
    For Each sht In book.Worksheets
        If sheetName = sht.Name Then
            SheetExists = True
            Exit Function
        End If
    Next
End Function

Public Function BookExists(ByVal bookName As String) As Boolean
    Dim book As Workbook
    BookExists = False
    For Each book In Workbooks
        If bookName = book.Name Then
            BookExists = True
            Exit Function
        End If
    Next
End Function

Public Function OpenSheet(ByVal book As Workbook, ByVal sheetName As String) As Worksheet
    Set OpenSheet = Nothing
    If SheetExists(book, sheetName) Then
        Set OpenSheet = book.Worksheets(sheetName)
    End If
End Function

Public Sub CloseBookIfOpenByMe(book As Workbook, Optional saveMe As Boolean = False)
    If dicOpenBook.Exists(book.Name) Then
        Exit Sub
    End If
    CloseBook book, saveMe
End Sub

Public Sub CloseBook(book As Workbook, Optional saveMe As Boolean = False)
    Application.DisplayAlerts = False
    If saveMe Then
        book.Save
    End If
   
    book.Close
    Set book = Nothing
    Application.DisplayAlerts = True
End Sub

Public Function OpenBook(ByVal sPath As String, ByVal bookName As String) As Workbook
    Set OpenBook = Nothing
    If BookExists(bookName) Then
        Set OpenBook = Workbooks(bookName)
        If Not dicOpenBook.Exists(bookName) Then dicOpenBook.Add bookName, True
        Exit Function
    End If
    If dicOpenBook.Exists(bookName) Then dicOpenBook.Remove bookName
On Error GoTo Err_
    Set OpenBook = Workbooks.Open(sPath & "\" & bookName)
Err_:
End Function

Public Sub Run()

    Dim opBook As Workbook, book As Workbook
    Dim opSht As Worksheet, sheet As Worksheet
    Dim data As Variant
    Dim sPath As String, bookName As String
    Dim r As Long, i As Long
    Dim answer  As Integer
    Dim datExists As Boolean
   
    Application.ScreenUpdating = False
   
    Set book = ThisWorkbook
   
    sPath = book.Path       ' Thu muc duong dan file nguon
    bookName = "Data.xlsx"  ' Ten file nguon
   
    Set opBook = OpenBook(sPath, bookName)
    If opBook Is Nothing Then
        MsgBox "Thong tin file nguon khong hop le", vbCritical + vbOKOnly
        Exit Sub
    End If
   
    Set opSht = OpenSheet(opBook, "Data")
    If opSht Is Nothing Then
        MsgBox "Thong tin sheet nguon khong hop le", vbCritical + vbOKOnly
        GoTo End_
    End If
   
    book.Activate
    Set sheet = book.ActiveSheet
   
    data = opSht.Range("A1").CurrentRegion.Value
    r = UBound(data, 1) + 1
    For i = LBound(data, 1) + 1 To UBound(data, 1)
        If data(i, 4) = sheet.Range("C4") And _
            data(i, 5) = sheet.Range("C5") Then
            r = i: datExists = True
            Exit For
        End If
    Next i

    If datExists Then
        answer = MsgBox("Du lieu da ton tai, ban co muon thay doi ?", vbYesNo + vbQuestion)
        If answer <> vbYes Then GoTo End_
    End If
   
    opSht.Cells(r, 1) = sheet.Range("C1")
    opSht.Cells(r, 2) = sheet.Range("C2")
    opSht.Cells(r, 3) = sheet.Range("C3")
    opSht.Cells(r, 4) = sheet.Range("C4")
    opSht.Cells(r, 5) = sheet.Range("C5")
    opSht.Cells(r, 6) = sheet.Range("C6")
    opSht.Cells(r, 7) = sheet.Range("C7")
   
    Application.ScreenUpdating = True
    CloseBookIfOpenByMe opBook, True
    MsgBox "Da xong!", vbInformation + vbOKOnly
   
    Exit Sub
   
End_:

    Application.ScreenUpdating = True
    CloseBookIfOpenByMe opBook, True

End Sub
 

File đính kèm

  • Data.xlsx
    8.8 KB · Đọc: 11
  • file dùng vba.xlsm
    24.8 KB · Đọc: 9
Upvote 0
Bạn tham khảo:
Mã:
Option Explicit

Dim dicOpenBook As New Dictionary

Public Function SheetExists(ByVal book As Workbook, ByVal sheetName As String) As Boolean
    Dim sht As Worksheet
    SheetExists = False
    For Each sht In book.Worksheets
        If sheetName = sht.Name Then
            SheetExists = True
            Exit Function
        End If
    Next
End Function

Public Function BookExists(ByVal bookName As String) As Boolean
    Dim book As Workbook
    BookExists = False
    For Each book In Workbooks
        If bookName = book.Name Then
            BookExists = True
            Exit Function
        End If
    Next
End Function

Public Function OpenSheet(ByVal book As Workbook, ByVal sheetName As String) As Worksheet
    Set OpenSheet = Nothing
    If SheetExists(book, sheetName) Then
        Set OpenSheet = book.Worksheets(sheetName)
    End If
End Function

Public Sub CloseBookIfOpenByMe(book As Workbook, Optional saveMe As Boolean = False)
    If dicOpenBook.Exists(book.Name) Then
        Exit Sub
    End If
    CloseBook book, saveMe
End Sub

Public Sub CloseBook(book As Workbook, Optional saveMe As Boolean = False)
    Application.DisplayAlerts = False
    If saveMe Then
        book.Save
    End If
  
    book.Close
    Set book = Nothing
    Application.DisplayAlerts = True
End Sub

Public Function OpenBook(ByVal sPath As String, ByVal bookName As String) As Workbook
    Set OpenBook = Nothing
    If BookExists(bookName) Then
        Set OpenBook = Workbooks(bookName)
        If Not dicOpenBook.Exists(bookName) Then dicOpenBook.Add bookName, True
        Exit Function
    End If
    If dicOpenBook.Exists(bookName) Then dicOpenBook.Remove bookName
On Error GoTo Err_
    Set OpenBook = Workbooks.Open(sPath & "\" & bookName)
Err_:
End Function

Public Sub Run()

    Dim opBook As Workbook, book As Workbook
    Dim opSht As Worksheet, sheet As Worksheet
    Dim data As Variant
    Dim sPath As String, bookName As String
    Dim r As Long, i As Long
    Dim answer  As Integer
    Dim datExists As Boolean
  
    Application.ScreenUpdating = False
  
    Set book = ThisWorkbook
  
    sPath = book.Path       ' Thu muc duong dan file nguon
    bookName = "Data.xlsx"  ' Ten file nguon
  
    Set opBook = OpenBook(sPath, bookName)
    If opBook Is Nothing Then
        MsgBox "Thong tin file nguon khong hop le", vbCritical + vbOKOnly
        Exit Sub
    End If
  
    Set opSht = OpenSheet(opBook, "Data")
    If opSht Is Nothing Then
        MsgBox "Thong tin sheet nguon khong hop le", vbCritical + vbOKOnly
        GoTo End_
    End If
  
    book.Activate
    Set sheet = book.ActiveSheet
  
    data = opSht.Range("A1").CurrentRegion.Value
    r = UBound(data, 1) + 1
    For i = LBound(data, 1) + 1 To UBound(data, 1)
        If data(i, 4) = sheet.Range("C4") And _
            data(i, 5) = sheet.Range("C5") Then
            r = i: datExists = True
            Exit For
        End If
    Next i

    If datExists Then
        answer = MsgBox("Du lieu da ton tai, ban co muon thay doi ?", vbYesNo + vbQuestion)
        If answer <> vbYes Then GoTo End_
    End If
  
    opSht.Cells(r, 1) = sheet.Range("C1")
    opSht.Cells(r, 2) = sheet.Range("C2")
    opSht.Cells(r, 3) = sheet.Range("C3")
    opSht.Cells(r, 4) = sheet.Range("C4")
    opSht.Cells(r, 5) = sheet.Range("C5")
    opSht.Cells(r, 6) = sheet.Range("C6")
    opSht.Cells(r, 7) = sheet.Range("C7")
  
    Application.ScreenUpdating = True
    CloseBookIfOpenByMe opBook, True
    MsgBox "Da xong!", vbInformation + vbOKOnly
  
    Exit Sub
  
End_:

    Application.ScreenUpdating = True
    CloseBookIfOpenByMe opBook, True

End Sub
Em cam on bac rat rat nhieu
 
Upvote 0
Như tiêu đề em đã viết, mong muốn có file A khi bấm VBA sẽ ghi một số nội dung sang file B
File B và file A sẽ không cùng một thư mục
Có ghi lại thời gian bấm
Nếu dữ liệu đã có thì update, nếu chưa có thì sẽ được ghi và căn cứ theo nội dung trong cột chính
Em cảm ơn cả nhà
Bạn sử dụng code sau và kiểm tra lại kết quả xem nhé!
PHP:
Option Explicit
Sub Truyen_DL()
    Dim Fso As Object, Item, Wb As Workbook, Lr&, k&, i&, Key$
    Dim Ws As Worksheet, Arr(), ten_khoa$, Ma_khoa$, Dic As Object
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Set Dic = CreateObject("Scripting.Dictionary")
    On Error Resume Next
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = True
        .Filters.Add "Microsoft Excel File", "*.xl*", 1
        If Not .Show Then Exit Sub
        For Each Item In .SelectedItems
            Set Wb = Workbooks.Open(Item)
            With Wb.Sheets("Data")
                Lr = .Range("D" & Rows.Count).End(xlUp).Row
                Arr = .Range("A2:G" & Lr).Value
                For i = 1 To UBound(Arr)
                    Key = Arr(i, 4) & "-" & Arr(i, 5)
                    If Not Dic.exists(Key) Then
                        k = k + 1
                        Dic.Add (Key), k
                    End If
                Next i
            End With
            With ThisWorkbook.Sheets("Sheet1")
                Key = .Cells(4, 3) & "-" & .Cells(5, 3)
                If Not Dic.exists(Key) Then
                    .Range("C1:C7").Copy
                    Wb.Sheets("Data").Range("A" & Lr + 1).Activate
                    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
                    False, Transpose:=True
                    Lr = Lr + 1
                    Application.CutCopyMode = False
                    With Wb.Sheets("Data")
                        If .Cells(i, 2) <> "" Then
                            .Cells(i, 1) = .Cells(i - 1, 1) + 1
                        End If
                    End With
                Else
                    ten_khoa = Split(Key, "-")(0)
                    Ma_khoa = Split(Key, "-")(1)
                    With Wb.Sheets("Data")
                        For i = 2 To Lr
                            If .Cells(i, 4) = ten_khoa And .Cells(i, 5) = Ma_khoa Then
                                ThisWorkbook.Sheets("Sheet1").Range("C1:C7").Copy
                                .Range("A" & i).Activate
                                Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
                                False, Transpose:=True
                                Application.CutCopyMode = False
                            End If
                            If .Cells(i, 2) <> "" Then
                                .Cells(i, 1) = .Cells(i - 1, 1) + 1
                            End If
                        Next i
                    End With
                End If
            End With
            Wb.Close True
        Next
    End With
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    MsgBox "Hoan Thanh"
    Set Dic = Nothing
End Sub
 
Upvote 0
Bạn sử dụng code sau và kiểm tra lại kết quả xem nhé!
PHP:
Option Explicit
Sub Truyen_DL()
    Dim Fso As Object, Item, Wb As Workbook, Lr&, k&, i&, Key$
    Dim Ws As Worksheet, Arr(), ten_khoa$, Ma_khoa$, Dic As Object
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    Set Dic = CreateObject("Scripting.Dictionary")
    On Error Resume Next
    With Application.FileDialog(msoFileDialogFilePicker)
        .AllowMultiSelect = True
        .Filters.Add "Microsoft Excel File", "*.xl*", 1
        If Not .Show Then Exit Sub
        For Each Item In .SelectedItems
            Set Wb = Workbooks.Open(Item)
            With Wb.Sheets("Data")
                Lr = .Range("D" & Rows.Count).End(xlUp).Row
                Arr = .Range("A2:G" & Lr).Value
                For i = 1 To UBound(Arr)
                    Key = Arr(i, 4) & "-" & Arr(i, 5)
                    If Not Dic.exists(Key) Then
                        k = k + 1
                        Dic.Add (Key), k
                    End If
                Next i
            End With
            With ThisWorkbook.Sheets("Sheet1")
                Key = .Cells(4, 3) & "-" & .Cells(5, 3)
                If Not Dic.exists(Key) Then
                    .Range("C1:C7").Copy
                    Wb.Sheets("Data").Range("A" & Lr + 1).Activate
                    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
                    False, Transpose:=True
                    Lr = Lr + 1
                    Application.CutCopyMode = False
                    With Wb.Sheets("Data")
                        If .Cells(i, 2) <> "" Then
                            .Cells(i, 1) = .Cells(i - 1, 1) + 1
                        End If
                    End With
                Else
                    ten_khoa = Split(Key, "-")(0)
                    Ma_khoa = Split(Key, "-")(1)
                    With Wb.Sheets("Data")
                        For i = 2 To Lr
                            If .Cells(i, 4) = ten_khoa And .Cells(i, 5) = Ma_khoa Then
                                ThisWorkbook.Sheets("Sheet1").Range("C1:C7").Copy
                                .Range("A" & i).Activate
                                Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
                                False, Transpose:=True
                                Application.CutCopyMode = False
                            End If
                            If .Cells(i, 2) <> "" Then
                                .Cells(i, 1) = .Cells(i - 1, 1) + 1
                            End If
                        Next i
                    End With
                End If
            End With
            Wb.Close True
        Next
    End With
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    MsgBox "Hoan Thanh"
    Set Dic = Nothing
End Sub
có thể nhờ bác xem giúp file được không, add vào nhưng khi chạy thì báo lỗi
1676132439128.png
và được bôi như hình 1676132473207.png
 

File đính kèm

  • MailMerge elearning v2.xlsm
    54.9 KB · Đọc: 5
Upvote 0
Bạn tham khảo cách làm khác:

Mã:
Option Explicit

Public Sub InsertOrUpdateData()
    
    Dim cnn As Object, rs As Object
    Dim strSQL As String, strConnection As String
    Dim strKhoa As String, strMon As String, strLop As String, strPhong As String, strGV As String
    Dim intNo As Integer, intMa As Integer

    With ThisWorkbook.Sheets("Sheet1")
        intNo = .Range("C1").Value
        strMon = .Range("C2").Value
        strLop = .Range("C3").Value
        strKhoa = .Range("C4").Value
        intMa = .Range("C5").Value
        strPhong = .Range("C6").Value
        strGV = .Range("C7").Value
    End With
    
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\B.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
    Set cnn = CreateObject("ADODB.Connection")
    
    cnn.Open strConnection
    strSQL = "SELECT COUNT(*) FROM [Data$] WHERE  [TEN_KHOA] = '" & strKhoa & "' AND [MA_KHOA] = " & intMa & ";"

    Set rs = CreateObject("ADODB.Recordset")
    Set rs = cnn.Execute(strSQL)
    
    If rs(0).Value = 0 Then
        strSQL = "INSERT INTO [Data$] ([TT],[TEN_MON],[TEN_LOP],[TEN_KHOA],[MA_KHOA],[PHONG_HOC],[GIANG_VIEN]) VALUES (" & intNo & ",'" & strMon & "','" & strLop & "','" & strKhoa & "'," & intMa & ",'" & strPhong & "','" & strGV & "');"
        cnn.Execute strSQL
    Else
        If MsgBox("Du lieu da ton tai,ban co muon thay doi khong?", vbYesNo + vbQuestion, "Xac nhan cap nhat") = vbYes Then
            strSQL = "UPDATE [Data$] SET [TT] =  " & intNo & ",[TEN_MON] = '" & strMon & "',[TEN_LOP] = '" & strLop & "',[TEN_KHOA] = '" & strKhoa & "',[MA_KHOA] =" & intMa & ",[GIANG_VIEN] ='" & strGV & "' WHERE [TEN_KHOA] = '" & strKhoa & "' AND [MA_KHOA] = " & intMa & ";"
            cnn.Execute strSQL
        Else
            GoTo End_
        End If
    End If
    
    MsgBox "OK,da cap nhat!", vbOKOnly + vbInformation
    
End_:

    rs.Close: Set rs = Nothing
    cnn.Close: Set cnn = Nothing
    
End Sub
 

File đính kèm

  • B.xlsx
    9.7 KB · Đọc: 6
  • Them sua - Form.xlsm
    29.2 KB · Đọc: 5
Upvote 0
Bạn tham khảo cách làm khác:

Mã:
Option Explicit

Public Sub InsertOrUpdateData()
   
    Dim cnn As Object, rs As Object
    Dim strSQL As String, strConnection As String
    Dim strKhoa As String, strMon As String, strLop As String, strPhong As String, strGV As String
    Dim intNo As Integer, intMa As Integer

    With ThisWorkbook.Sheets("Sheet1")
        intNo = .Range("C1").Value
        strMon = .Range("C2").Value
        strLop = .Range("C3").Value
        strKhoa = .Range("C4").Value
        intMa = .Range("C5").Value
        strPhong = .Range("C6").Value
        strGV = .Range("C7").Value
    End With
   
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ThisWorkbook.Path & "\B.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
    Set cnn = CreateObject("ADODB.Connection")
   
    cnn.Open strConnection
    strSQL = "SELECT COUNT(*) FROM [Data$] WHERE  [TEN_KHOA] = '" & strKhoa & "' AND [MA_KHOA] = " & intMa & ";"

    Set rs = CreateObject("ADODB.Recordset")
    Set rs = cnn.Execute(strSQL)
   
    If rs(0).Value = 0 Then
        strSQL = "INSERT INTO [Data$] ([TT],[TEN_MON],[TEN_LOP],[TEN_KHOA],[MA_KHOA],[PHONG_HOC],[GIANG_VIEN]) VALUES (" & intNo & ",'" & strMon & "','" & strLop & "','" & strKhoa & "'," & intMa & ",'" & strPhong & "','" & strGV & "');"
        cnn.Execute strSQL
    Else
        If MsgBox("Du lieu da ton tai,ban co muon thay doi khong?", vbYesNo + vbQuestion, "Xac nhan cap nhat") = vbYes Then
            strSQL = "UPDATE [Data$] SET [TT] =  " & intNo & ",[TEN_MON] = '" & strMon & "',[TEN_LOP] = '" & strLop & "',[TEN_KHOA] = '" & strKhoa & "',[MA_KHOA] =" & intMa & ",[GIANG_VIEN] ='" & strGV & "' WHERE [TEN_KHOA] = '" & strKhoa & "' AND [MA_KHOA] = " & intMa & ";"
            cnn.Execute strSQL
        Else
            GoTo End_
        End If
    End If
   
    MsgBox "OK,da cap nhat!", vbOKOnly + vbInformation
   
End_:

    rs.Close: Set rs = Nothing
    cnn.Close: Set cnn = Nothing
   
End Sub
Cảm ơn bác nhiều, File có thể chạy nhưng nhiều mục mình muốn sửa code để phù hợp hơn với file thì nhìn hơi khó, Hình như bác lấy tên file B của Sheet data nên nếu dòng 1 mà bị đổi thì sẽ lỗi nếu chuyển sang file khác
 
Upvote 0
Web KT

Bài viết mới nhất

Back
Top Bottom