Xin hướng dẫn cách trích xuất dữ liệu từ outlook ra excel

Liên hệ QC

ducleminh

Thành viên chính thức
Tham gia
3/10/07
Bài viết
66
Được thích
3
Thân gởi các bạn
Hiện tại mình dùng outlook để soạn gởi email trong công việc
Trong mục quản lý của outlook có thể hiện các thông số của các email nhận và gởi như:
- From (to)
- Subject
- Received (sent) time

Nay, mình muốn trích xuất các thông số đó ra exel để tính toán ( đặc biệt là thông số received (sent) time)
Mình có search trên diễn đàn thì có đọc được topic này,ko biết có phù hợp ko,và mình cũng chưa hiểu về topic này lắm
http://www.giaiphapexcel.com/forum/showthread.php?9654-lấy-dữ-liệu-từ-outlook


Mong các bạn hướng dẫn mình trích xuất với
Cám ơn các bạn
 
Thân gởi các bạnHiện tại mình dùng outlook để soạn gởi email trong công việcTrong mục quản lý của outlook có thể hiện các thông số của các email nhận và gởi như: - From (to) - Subject - Received (sent) timeNay, mình muốn trích xuất các thông số đó ra exel để tính toán ( đặc biệt là thông số received (sent) time)Mình có search trên diễn đàn thì có đọc được topic này,ko biết có phù hợp ko,và mình cũng chưa hiểu về topic này lắmhttp://www.giaiphapexcel.com/forum/showthread.php?9654-l%E1%BA%A5y-d%E1%BB%AF-li%E1%BB%87u-t%E1%BB%AB-outlookMong các bạn hướng dẫn mình trích xuất vớiCám ơn các bạn
Bạn chạy code sau, khi chạy code bạn phải chọn folder trong mail cần xuất ra Excel nhé

Mã:
Sub ToExcel()
    On Error GoTo ErrHandler
    Dim appExcel As Excel.Application, wkb As Excel.Workbook, wks As Excel.Worksheet, rng As Excel.Range
    Dim intRowCounter As Integer, intColumnCounter As Integer
    Dim msg As Outlook.MailItem, nms As Outlook.Namespace, fld As Outlook.MAPIFolder, itm As Object
    Debug.Print strSheet
    'Select export folder
    Set nms = Application.GetNamespace("MAPI")
    Set fld = nms.PickFolder
    'Handle potential errors with Select Folder dialog box.
    If fld Is Nothing Then
        MsgBox "There are no mail messages to export", vbOKOnly, "Error"
        Exit Sub
    ElseIf fld.DefaultItemType <> olMailItem Then
        MsgBox "There are no mail messages to export", vbOKOnly, "Error"
        Exit Sub
    ElseIf fld.Items.Count = 0 Then
        MsgBox "There are no mail messages to export", vbOKOnly, "Error"
        Exit Sub
    End If
    'Add new and activate Excel workbook.
    Set appExcel = CreateObject("Excel.Application")
    appExcel.Workbooks.Add
    Set wkb = appExcel.ActiveWorkbook
    Set wks = wkb.Sheets(1)
    wks.Activate
    appExcel.Application.Visible = True
    'Copy field items in mail folder.
    For Each itm In fld.Items
        intColumnCounter = 1
        Set msg = itm
        intRowCounter = intRowCounter + 1
        Set rng = wks.Cells(intRowCounter, intColumnCounter)
        rng.Value = msg.To
        intColumnCounter = intColumnCounter + 1
        Set rng = wks.Cells(intRowCounter, intColumnCounter)
        rng.Value = msg.SenderEmailAddress
        intColumnCounter = intColumnCounter + 1
        Set rng = wks.Cells(intRowCounter, intColumnCounter)
        rng.Value = msg.Subject
        intColumnCounter = intColumnCounter + 1
        Set rng = wks.Cells(intRowCounter, intColumnCounter)
        rng.Value = msg.Body
        intColumnCounter = intColumnCounter + 1
        Set rng = wks.Cells(intRowCounter, intColumnCounter)
        rng.Value = msg.SentOn
        intColumnCounter = intColumnCounter + 1
        Set rng = wks.Cells(intRowCounter, intColumnCounter)
        rng.Value = msg.ReceivedTime
    Next itm
    Set wks = Nothing: Set rng = Nothing: Set msg = Nothing: Set wkb = Nothing
    Set nms = Nothing: Set fld = Nothing: Set itm = Nothing: Set appExcel = Nothing
    Exit Sub
ErrHandler:     If Err.Number = 1004 Then
        MsgBox strSheet & " doesn't exist", vbOKOnly, "Error"
    Else
        MsgBox Err.Number & "; Description: ", vbOKOnly, "Error"
    End If
    Set appExcel = Nothing: Set wkb = Nothing: Set wks = Nothing: Set rng = Nothing
    Set msg = Nothing: Set nms = Nothing: Set fld = Nothing: Set itm = Nothing

End Sub
 
Chỉnh sửa lần cuối bởi điều hành viên:
Cám ơn bạn nhiều lắm
Nhưng khi chọn Atl F8 để Run code thì nó báo lỗi

Loi code email.jpg

Nhấn enter thì nó tô vàng chỗ này
Sub ToExcel()

Bạn hướng dẫn mình khắc phục với
Mình chưa hiểu chỗ "chọn folder trong mail cần xuất ra Excel nhé" là thực hiện khi nào ?

Cám ơn bạn lần nữa nhé
 
Lần chỉnh sửa cuối:
Cám ơn bạn nhiều lắm
Nhưng khi chọn Atl F8 để Run code thì nó báo lỗi, tô vàng chỗ này

Sub ToExcel()

Bạn hướng dẫn mình khắc phục với
Mình chưa hiểu chỗ "chọn folder trong mail cần xuất ra Excel nhé" là thực hiện khi nào ?

Cám ơn bạn lần nữa nhé
1.) Bạn vào Outlook, chọn Tools/Macro/Security, xong chọn Low... Nhấn Ok, thoát Outlook.
2.) Mở Outlook, nhấn tổ hợp phím Alt+F11, dán code trên vào Module, rồi nhấn F5 chạy code đó.
3.) Khi chạy code nó có hiện hộp Dialog đòi bạn phải chọn mục cần xuất ra. (Ví dụ bạn chọn mục Inbox thì nó sẽ xuất toàn bộ mục này sang Excel)
 
1.) Bạn vào Outlook, chọn Tools/Macro/Security, xong chọn Low... Nhấn Ok, thoát Outlook.
2.) Mở Outlook, nhấn tổ hợp phím Alt+F11, dán code trên vào Module, rồi nhấn F5 chạy code đó.
3.) Khi chạy code nó có hiện hộp Dialog đòi bạn phải chọn mục cần xuất ra. (Ví dụ bạn chọn mục Inbox thì nó sẽ xuất toàn bộ mục này sang Excel)

Cám ơn bạn, mình đã làm giống bạn, nhưng khi bấm F5 vẫn bị báo lỗi như hình dưới, lần này là quét xanh dòng chữ "Dim appExcel As Excel.Application "

Loi code email.jpg

Mình đang sử dụng Microsolf Outlook 2007, khi chọn Tool> Marco > Security > thì không có phần Low như bạn hướng dẫn
Mà chỉ có các lựa chọn:
+ No warning and disable all macros code
+ Warning for signed macros; all unsigned macros are disabled
+ Warning for all macros
+ No security check for macros (Not recommended)

Mình đã chọn lựa chọn thứ 4

Bạn hướng dẫn mình thêm với, cám ơn bạn nhiều
 
Chỉnh sửa lần cuối bởi điều hành viên:
Bạn nhấn tổ hợp phím ALT+F11 để vào cửa sổ VB, chọn Tools, Reference, click chọn vào Microsoft Excel xx.x Object Library rồi nhấn OK thử chạy code lại nhé.
 
Không hiểu sao, mình cũng bị lỗi ở dòng


Mình đã vào Bạn nhấn tổ hợp phím ALT+F11 để vào cửa sổ VB, chọn Tools, Reference, click chọn vào Microsoft Excel 12.0 Object Library nhưng mà vẫn bị lỗi chỗ này


Không biết mình có tích thiếu cái gì không?
 
Không hiểu sao, mình cũng bị lỗi ở dòng



Mình đã vào Bạn nhấn tổ hợp phím ALT+F11 để vào cửa sổ VB, chọn Tools, Reference, click chọn vào Microsoft Excel 12.0 Object Library nhưng mà vẫn bị lỗi chỗ này


Không biết mình có tích thiếu cái gì không?
Code nằm trong Outlook nghen bạn
 
có cách nào hay phím tắt nào mà chỉ cần click vào nó là code chạy ko hả a? muốn run code thì phải vào macros sau đó run code thì hơi bất tiện...
mà hình như code này mỗi lần em run code nó chỉ xuất ra mail to , cc, subject chứ ko xuất file đính kèm ạ
 
Code nằm trong Outlook nghen bạn
Mừng quá... mình tìm ra được vấn đề cần thiết.
Anh Hai Lúa Miền Tây ơi, nhờ Anh giúp thêm vấn đề này với:
Khi mình chạy code này, Outlook sẽ xuất hết email trong folder.
Tuy nhiên, hôm trước mình đã xuất rồi, giờ chỉ cần xuất thêm những email mới thôi thì mình cần thêm code như thế nào vậy Anh ???
VD: mình có thể thêm yêu cầu xuất email từ ngày nào đến ngày nào ko Anh ??
Cảm ơn Anh nhiều
 
Bác Hai Lúa Miền Tây ơi, bác cho em hỏi nhờ 1 chút là em xuất được mail ra excel rồi nhưng mà khi em chọn xuất từ hộp thư đến thì nó chỉ đc vài 3 email mà k phải tất cả email, giờ nếu em muốn xuất toàn bộ mail thì phải làm như thế nào ạ ? em cảm ơn
 
Lỗi này khắc phục thế nào a nhỉ?

1570118898342.png
 
Lỗi này khắc phục thế nào a nhỉ?

View attachment 226095
anh hai lúa ơi!
em chạy code xong nó trích xuất ra file có các ngày không tới thời điểm hiện tại, có cách nào khắc phục không anh?
mong phản hồi sớm từ anh, vì công việc của em thực sự cần cách này!
Hai bạn thử code này xem sao nhé:
Rich (BB code):
Option Explicit
 Sub CopyToExcel()
 Dim xlApp As Object
 Dim xlWB As Object
 Dim xlSheet As Object
 Dim rCount As Long
 Dim bXStarted As Boolean
 Dim enviro As String
 Dim strPath As String

 Dim currentExplorer As Explorer
 Dim Selection As Selection
 Dim olItem As Outlook.MailItem
 Dim obj As Object
 Dim strColA, strColB, strColC, strColD, strColE As String
               
' Get Excel set up
     On Error Resume Next
     Set xlApp = GetObject(, "Excel.Application")
     If Err <> 0 Then
         Application.StatusBar = "Please wait while Excel source is opened ... "
         Set xlApp = CreateObject("Excel.Application")
         bXStarted = True
     End If
     On Error GoTo 0
     
'## Open a specific workbook to input the data
'the path of the workbook under the windows user account
'enviro = CStr(Environ("USERPROFILE"))
' strPath = enviro & "\Documents\test.xlsx"
'     Set xlWB = xlApp.Workbooks.Open(strPath)
'     Set xlSheet = xlWB.Sheets("Sheet1")
'## End Specific workbook

'## Use New Workbook
Set xlWB = xlApp.Workbooks.Add
Set xlSheet = xlWB.Sheets("Sheet1")
'## end use new workbook

' Add column names
  xlSheet.Range("A1") = "Sender"
  xlSheet.Range("B1") = "Sender address"
  xlSheet.Range("C1") = "Message Body"
  xlSheet.Range("D1") = "Sent To"
  xlSheet.Range("E1") = "Recieved Time"

' Process the message record
    
  On Error Resume Next
'Find the next empty line of the worksheet
rCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(-4162).Row
'needed for Exchange 2016. Remove if causing blank lines.
rCount = rCount + 1

' get the values from outlook
Set currentExplorer = Application.ActiveExplorer
Set Selection = currentExplorer.Selection
  For Each obj In Selection

    Set olItem = obj
    
 'collect the fields
    strColA = olItem.SenderName
    strColB = olItem.SenderEmailAddress
    strColC = olItem.Body
    strColD = olItem.To
    strColE = olItem.ReceivedTime
    
'### Get all recipient addresses
' instead of To names
Dim strRecipients As String
Dim Recipient As Outlook.Recipient
For Each Recipient In olItem.Recipients
 strRecipients = Recipient.Address & "; " & strRecipients
 Next Recipient

  strColD = strRecipients
'### end all recipients addresses

'### Get the Exchange address
' if not using Exchange, this block can be removed
 Dim olEU As Outlook.ExchangeUser
 Dim oEDL As Outlook.ExchangeDistributionList
 Dim recip As Outlook.Recipient
 Set recip = Application.Session.CreateRecipient(strColB)

If InStr(1, strColB, "/") > 0 Then
' if exchange, get smtp address
    Select Case recip.AddressEntry.AddressEntryUserType
       Case OlAddressEntryUserType.olExchangeUserAddressEntry
         Set olEU = recip.AddressEntry.GetExchangeUser
         If Not (olEU Is Nothing) Then
             strColB = olEU.PrimarySmtpAddress
         End If
       Case OlAddressEntryUserType.olOutlookContactAddressEntry
         Set olEU = recip.AddressEntry.GetExchangeUser
         If Not (olEU Is Nothing) Then
            strColB = olEU.PrimarySmtpAddress
         End If
       Case OlAddressEntryUserType.olExchangeDistributionListAddressEntry
         Set oEDL = recip.AddressEntry.GetExchangeDistributionList
         If Not (oEDL Is Nothing) Then
            strColB = olEU.PrimarySmtpAddress
         End If
     End Select
End If
' ### End Exchange section

'write them in the excel sheet
  xlSheet.Range("A" & rCount) = strColA ' sender name
  xlSheet.Range("B" & rCount) = strColB ' sender address
  xlSheet.Range("C" & rCount) = strColC ' message body
  xlSheet.Range("D" & rCount) = strColD ' sent to
  xlSheet.Range("E" & rCount) = strColE ' recieved time
 
'Next row
  rCount = rCount + 1

' size the cells
    xlSheet.Columns("A:E").EntireColumn.AutoFit
    xlSheet.Columns("C:C").ColumnWidth = 100
    xlSheet.Columns("D:D").ColumnWidth = 30
    xlSheet.Range("A2").Select
    xlSheet.Columns("A:E").VerticalAlignment = xlTop

 Next
 xlApp.Visible = True

' to save but not close
'xlWB.Save

' to save and close
'     xlWB.Close 1
'     If bXStarted Then
'         xlApp.Quit
'     End If
' end save and close
    
     Set olItem = Nothing
     Set obj = Nothing
     Set currentExplorer = Nothing
     Set xlSheet = Nothing
     Set xlWB = Nothing
     Set xlApp = Nothing
 End Sub
Cách dùng:

1/ Chọn folder mail cần Export ra Excel
2/ Chọn tiếp những mail cần cần Export ra Excel
3/ Bấm phím alt + f8 rồi click chọn chạy sub: "CopyToExcel"

Chúc các bạn thành công !
 
Hai bạn thử code này xem sao nhé:
Rich (BB code):
Option Explicit
Sub CopyToExcel()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim rCount As Long
Dim bXStarted As Boolean
Dim enviro As String
Dim strPath As String

Dim currentExplorer As Explorer
Dim Selection As Selection
Dim olItem As Outlook.MailItem
Dim obj As Object
Dim strColA, strColB, strColC, strColD, strColE As String
              
' Get Excel set up
     On Error Resume Next
     Set xlApp = GetObject(, "Excel.Application")
     If Err <> 0 Then
         Application.StatusBar = "Please wait while Excel source is opened ... "
         Set xlApp = CreateObject("Excel.Application")
         bXStarted = True
     End If
     On Error GoTo 0
    
'## Open a specific workbook to input the data
'the path of the workbook under the windows user account
'enviro = CStr(Environ("USERPROFILE"))
' strPath = enviro & "\Documents\test.xlsx"
'     Set xlWB = xlApp.Workbooks.Open(strPath)
'     Set xlSheet = xlWB.Sheets("Sheet1")
'## End Specific workbook

'## Use New Workbook
Set xlWB = xlApp.Workbooks.Add
Set xlSheet = xlWB.Sheets("Sheet1")
'## end use new workbook

' Add column names
  xlSheet.Range("A1") = "Sender"
  xlSheet.Range("B1") = "Sender address"
  xlSheet.Range("C1") = "Message Body"
  xlSheet.Range("D1") = "Sent To"
  xlSheet.Range("E1") = "Recieved Time"

' Process the message record
   
  On Error Resume Next
'Find the next empty line of the worksheet
rCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(-4162).Row
'needed for Exchange 2016. Remove if causing blank lines.
rCount = rCount + 1

' get the values from outlook
Set currentExplorer = Application.ActiveExplorer
Set Selection = currentExplorer.Selection
  For Each obj In Selection

    Set olItem = obj
   
'collect the fields
    strColA = olItem.SenderName
    strColB = olItem.SenderEmailAddress
    strColC = olItem.Body
    strColD = olItem.To
    strColE = olItem.ReceivedTime
   
'### Get all recipient addresses
' instead of To names
Dim strRecipients As String
Dim Recipient As Outlook.Recipient
For Each Recipient In olItem.Recipients
strRecipients = Recipient.Address & "; " & strRecipients
Next Recipient

  strColD = strRecipients
'### end all recipients addresses

'### Get the Exchange address
' if not using Exchange, this block can be removed
Dim olEU As Outlook.ExchangeUser
Dim oEDL As Outlook.ExchangeDistributionList
Dim recip As Outlook.Recipient
Set recip = Application.Session.CreateRecipient(strColB)

If InStr(1, strColB, "/") > 0 Then
' if exchange, get smtp address
    Select Case recip.AddressEntry.AddressEntryUserType
       Case OlAddressEntryUserType.olExchangeUserAddressEntry
         Set olEU = recip.AddressEntry.GetExchangeUser
         If Not (olEU Is Nothing) Then
             strColB = olEU.PrimarySmtpAddress
         End If
       Case OlAddressEntryUserType.olOutlookContactAddressEntry
         Set olEU = recip.AddressEntry.GetExchangeUser
         If Not (olEU Is Nothing) Then
            strColB = olEU.PrimarySmtpAddress
         End If
       Case OlAddressEntryUserType.olExchangeDistributionListAddressEntry
         Set oEDL = recip.AddressEntry.GetExchangeDistributionList
         If Not (oEDL Is Nothing) Then
            strColB = olEU.PrimarySmtpAddress
         End If
     End Select
End If
' ### End Exchange section

'write them in the excel sheet
  xlSheet.Range("A" & rCount) = strColA ' sender name
  xlSheet.Range("B" & rCount) = strColB ' sender address
  xlSheet.Range("C" & rCount) = strColC ' message body
  xlSheet.Range("D" & rCount) = strColD ' sent to
  xlSheet.Range("E" & rCount) = strColE ' recieved time

'Next row
  rCount = rCount + 1

' size the cells
    xlSheet.Columns("A:E").EntireColumn.AutoFit
    xlSheet.Columns("C:C").ColumnWidth = 100
    xlSheet.Columns("D:D").ColumnWidth = 30
    xlSheet.Range("A2").Select
    xlSheet.Columns("A:E").VerticalAlignment = xlTop

Next
xlApp.Visible = True

' to save but not close
'xlWB.Save

' to save and close
'     xlWB.Close 1
'     If bXStarted Then
'         xlApp.Quit
'     End If
' end save and close
   
     Set olItem = Nothing
     Set obj = Nothing
     Set currentExplorer = Nothing
     Set xlSheet = Nothing
     Set xlWB = Nothing
     Set xlApp = Nothing
End Sub
Cách dùng:

1/ Chọn folder mail cần Export ra Excel
2/ Chọn tiếp những mail cần cần Export ra Excel
3/ Bấm phím alt + f8 rồi click chọn chạy sub: "CopyToExcel"

Chúc các bạn thành công !

Chạy ngon a ơi.

Thanks a ;)
 
Hai bạn thử code này xem sao nhé:
Rich (BB code):
Option Explicit
Sub CopyToExcel()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim rCount As Long
Dim bXStarted As Boolean
Dim enviro As String
Dim strPath As String

Dim currentExplorer As Explorer
Dim Selection As Selection
Dim olItem As Outlook.MailItem
Dim obj As Object
Dim strColA, strColB, strColC, strColD, strColE As String
              
' Get Excel set up
     On Error Resume Next
     Set xlApp = GetObject(, "Excel.Application")
     If Err <> 0 Then
         Application.StatusBar = "Please wait while Excel source is opened ... "
         Set xlApp = CreateObject("Excel.Application")
         bXStarted = True
     End If
     On Error GoTo 0
    
'## Open a specific workbook to input the data
'the path of the workbook under the windows user account
'enviro = CStr(Environ("USERPROFILE"))
' strPath = enviro & "\Documents\test.xlsx"
'     Set xlWB = xlApp.Workbooks.Open(strPath)
'     Set xlSheet = xlWB.Sheets("Sheet1")
'## End Specific workbook

'## Use New Workbook
Set xlWB = xlApp.Workbooks.Add
Set xlSheet = xlWB.Sheets("Sheet1")
'## end use new workbook

' Add column names
  xlSheet.Range("A1") = "Sender"
  xlSheet.Range("B1") = "Sender address"
  xlSheet.Range("C1") = "Message Body"
  xlSheet.Range("D1") = "Sent To"
  xlSheet.Range("E1") = "Recieved Time"

' Process the message record
   
  On Error Resume Next
'Find the next empty line of the worksheet
rCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(-4162).Row
'needed for Exchange 2016. Remove if causing blank lines.
rCount = rCount + 1

' get the values from outlook
Set currentExplorer = Application.ActiveExplorer
Set Selection = currentExplorer.Selection
  For Each obj In Selection

    Set olItem = obj
   
'collect the fields
    strColA = olItem.SenderName
    strColB = olItem.SenderEmailAddress
    strColC = olItem.Body
    strColD = olItem.To
    strColE = olItem.ReceivedTime
   
'### Get all recipient addresses
' instead of To names
Dim strRecipients As String
Dim Recipient As Outlook.Recipient
For Each Recipient In olItem.Recipients
strRecipients = Recipient.Address & "; " & strRecipients
Next Recipient

  strColD = strRecipients
'### end all recipients addresses

'### Get the Exchange address
' if not using Exchange, this block can be removed
Dim olEU As Outlook.ExchangeUser
Dim oEDL As Outlook.ExchangeDistributionList
Dim recip As Outlook.Recipient
Set recip = Application.Session.CreateRecipient(strColB)

If InStr(1, strColB, "/") > 0 Then
' if exchange, get smtp address
    Select Case recip.AddressEntry.AddressEntryUserType
       Case OlAddressEntryUserType.olExchangeUserAddressEntry
         Set olEU = recip.AddressEntry.GetExchangeUser
         If Not (olEU Is Nothing) Then
             strColB = olEU.PrimarySmtpAddress
         End If
       Case OlAddressEntryUserType.olOutlookContactAddressEntry
         Set olEU = recip.AddressEntry.GetExchangeUser
         If Not (olEU Is Nothing) Then
            strColB = olEU.PrimarySmtpAddress
         End If
       Case OlAddressEntryUserType.olExchangeDistributionListAddressEntry
         Set oEDL = recip.AddressEntry.GetExchangeDistributionList
         If Not (oEDL Is Nothing) Then
            strColB = olEU.PrimarySmtpAddress
         End If
     End Select
End If
' ### End Exchange section

'write them in the excel sheet
  xlSheet.Range("A" & rCount) = strColA ' sender name
  xlSheet.Range("B" & rCount) = strColB ' sender address
  xlSheet.Range("C" & rCount) = strColC ' message body
  xlSheet.Range("D" & rCount) = strColD ' sent to
  xlSheet.Range("E" & rCount) = strColE ' recieved time

'Next row
  rCount = rCount + 1

' size the cells
    xlSheet.Columns("A:E").EntireColumn.AutoFit
    xlSheet.Columns("C:C").ColumnWidth = 100
    xlSheet.Columns("D:D").ColumnWidth = 30
    xlSheet.Range("A2").Select
    xlSheet.Columns("A:E").VerticalAlignment = xlTop

Next
xlApp.Visible = True

' to save but not close
'xlWB.Save

' to save and close
'     xlWB.Close 1
'     If bXStarted Then
'         xlApp.Quit
'     End If
' end save and close
   
     Set olItem = Nothing
     Set obj = Nothing
     Set currentExplorer = Nothing
     Set xlSheet = Nothing
     Set xlWB = Nothing
     Set xlApp = Nothing
End Sub
Cách dùng:

1/ Chọn folder mail cần Export ra Excel
2/ Chọn tiếp những mail cần cần Export ra Excel
3/ Bấm phím alt + f8 rồi click chọn chạy sub: "CopyToExcel"

Chúc các bạn thành công !
Bác ơi, em dùng outlook 2016 chưa activation nên không chạy được đúng không ạ, em nhấn tổ hợp ALT + F8 ko thấy xuất hiện sub để chạy
 
Bác ơi, em dùng outlook 2016 chưa activation nên không chạy được đúng không ạ, em nhấn tổ hợp ALT + F8 ko thấy xuất hiện sub để chạy
Bạn kiểm tra xem đã thiết lập Enable macro chưa? Nếu chưa thì bạn click tab File/Option/Trust Center rồi bấm chọn như trong hình:

1598318129503.png

Bấm Ok, rồi nhấn tổ hợp phím ALT+F11 để vào cửa sổ VB, bấm chuột phải vào Project1, Insert/Module, rồi dán đoạn code vô:
PHP:
Option Explicit
 Sub CopyToExcel()
 Dim xlApp As Object
 Dim xlWB As Object
 Dim xlSheet As Object
 Dim rCount As Long
 Dim bXStarted As Boolean
 Dim enviro As String
 Dim strPath As String

 Dim currentExplorer As Explorer
 Dim Selection As Selection
 Dim olItem As Outlook.MailItem
 Dim obj As Object
 Dim strColA, strColB, strColC, strColD, strColE As String
              
' Get Excel set up
     On Error Resume Next
     Set xlApp = GetObject(, "Excel.Application")
     If Err <> 0 Then
         Application.StatusBar = "Please wait while Excel source is opened ... "
         Set xlApp = CreateObject("Excel.Application")
         bXStarted = True
     End If
     On Error GoTo 0
    
'## Open a specific workbook to input the data
'the path of the workbook under the windows user account
'enviro = CStr(Environ("USERPROFILE"))
' strPath = enviro & "\Documents\test.xlsx"
'     Set xlWB = xlApp.Workbooks.Open(strPath)
'     Set xlSheet = xlWB.Sheets("Sheet1")
'## End Specific workbook

'## Use New Workbook
Set xlWB = xlApp.Workbooks.Add
Set xlSheet = xlWB.Sheets("Sheet1")
'## end use new workbook

' Add column names
  xlSheet.Range("A1") = "Sender"
  xlSheet.Range("B1") = "Sender address"
  xlSheet.Range("C1") = "Message Body"
  xlSheet.Range("D1") = "Sent To"
  xlSheet.Range("E1") = "Recieved Time"

' Process the message record
    
  On Error Resume Next
'Find the next empty line of the worksheet
rCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(-4162).Row
'needed for Exchange 2016. Remove if causing blank lines.
rCount = rCount + 1

' get the values from outlook
Set currentExplorer = Application.ActiveExplorer
Set Selection = currentExplorer.Selection
  For Each obj In Selection

    Set olItem = obj
    
 'collect the fields
    strColA = olItem.SenderName
    strColB = olItem.SenderEmailAddress
    strColC = olItem.Body
    strColD = olItem.To
    strColE = olItem.ReceivedTime
    
'### Get all recipient addresses
' instead of To names
Dim strRecipients As String
Dim Recipient As Outlook.Recipient
For Each Recipient In olItem.Recipients
 strRecipients = Recipient.Address & "; " & strRecipients
 Next Recipient

  strColD = strRecipients
'### end all recipients addresses

'### Get the Exchange address
' if not using Exchange, this block can be removed
 Dim olEU As Outlook.ExchangeUser
 Dim oEDL As Outlook.ExchangeDistributionList
 Dim recip As Outlook.Recipient
 Set recip = Application.Session.CreateRecipient(strColB)

If InStr(1, strColB, "/") > 0 Then
' if exchange, get smtp address
    Select Case recip.AddressEntry.AddressEntryUserType
       Case OlAddressEntryUserType.olExchangeUserAddressEntry
         Set olEU = recip.AddressEntry.GetExchangeUser
         If Not (olEU Is Nothing) Then
             strColB = olEU.PrimarySmtpAddress
         End If
       Case OlAddressEntryUserType.olOutlookContactAddressEntry
         Set olEU = recip.AddressEntry.GetExchangeUser
         If Not (olEU Is Nothing) Then
            strColB = olEU.PrimarySmtpAddress
         End If
       Case OlAddressEntryUserType.olExchangeDistributionListAddressEntry
         Set oEDL = recip.AddressEntry.GetExchangeDistributionList
         If Not (oEDL Is Nothing) Then
            strColB = olEU.PrimarySmtpAddress
         End If
     End Select
End If
' ### End Exchange section

'write them in the excel sheet
  xlSheet.Range("A" & rCount) = strColA ' sender name
  xlSheet.Range("B" & rCount) = strColB ' sender address
  xlSheet.Range("C" & rCount) = strColC ' message body
  xlSheet.Range("D" & rCount) = strColD ' sent to
  xlSheet.Range("E" & rCount) = strColE ' recieved time
 
'Next row
  rCount = rCount + 1

' size the cells
    xlSheet.Columns("A:E").EntireColumn.AutoFit
    xlSheet.Columns("C:C").ColumnWidth = 100
    xlSheet.Columns("D:D").ColumnWidth = 30
    xlSheet.Range("A2").Select
    xlSheet.Columns("A:E").VerticalAlignment = xlTop

 Next
 xlApp.Visible = True

' to save but not close
'xlWB.Save

' to save and close
'     xlWB.Close 1
'     If bXStarted Then
'         xlApp.Quit
'     End If
' end save and close
    
     Set olItem = Nothing
     Set obj = Nothing
     Set currentExplorer = Nothing
     Set xlSheet = Nothing
     Set xlWB = Nothing
     Set xlApp = Nothing
 End Sub

Nhấn tiếp chọn tab Tools, Reference, click chọn vào Microsoft Excel 16.0 Object Library :

1598318465709.png
Nhấn OK, rồi thoát Outlook và thử chạy lại xem được không nhé!
 
Lần chỉnh sửa cuối:
Hai bạn thử code này xem sao nhé:
Rich (BB code):
Option Explicit
 Sub CopyToExcel()
 Dim xlApp As Object
 Dim xlWB As Object
 Dim xlSheet As Object
 Dim rCount As Long
 Dim bXStarted As Boolean
 Dim enviro As String
 Dim strPath As String

 Dim currentExplorer As Explorer
 Dim Selection As Selection
 Dim olItem As Outlook.MailItem
 Dim obj As Object
 Dim strColA, strColB, strColC, strColD, strColE As String
              
' Get Excel set up
     On Error Resume Next
     Set xlApp = GetObject(, "Excel.Application")
     If Err <> 0 Then
         Application.StatusBar = "Please wait while Excel source is opened ... "
         Set xlApp = CreateObject("Excel.Application")
         bXStarted = True
     End If
     On Error GoTo 0
    
'## Open a specific workbook to input the data
'the path of the workbook under the windows user account
'enviro = CStr(Environ("USERPROFILE"))
' strPath = enviro & "\Documents\test.xlsx"
'     Set xlWB = xlApp.Workbooks.Open(strPath)
'     Set xlSheet = xlWB.Sheets("Sheet1")
'## End Specific workbook

'## Use New Workbook
Set xlWB = xlApp.Workbooks.Add
Set xlSheet = xlWB.Sheets("Sheet1")
'## end use new workbook

' Add column names
  xlSheet.Range("A1") = "Sender"
  xlSheet.Range("B1") = "Sender address"
  xlSheet.Range("C1") = "Message Body"
  xlSheet.Range("D1") = "Sent To"
  xlSheet.Range("E1") = "Recieved Time"

' Process the message record
   
  On Error Resume Next
'Find the next empty line of the worksheet
rCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(-4162).Row
'needed for Exchange 2016. Remove if causing blank lines.
rCount = rCount + 1

' get the values from outlook
Set currentExplorer = Application.ActiveExplorer
Set Selection = currentExplorer.Selection
  For Each obj In Selection

    Set olItem = obj
   
 'collect the fields
    strColA = olItem.SenderName
    strColB = olItem.SenderEmailAddress
    strColC = olItem.Body
    strColD = olItem.To
    strColE = olItem.ReceivedTime
   
'### Get all recipient addresses
' instead of To names
Dim strRecipients As String
Dim Recipient As Outlook.Recipient
For Each Recipient In olItem.Recipients
 strRecipients = Recipient.Address & "; " & strRecipients
 Next Recipient

  strColD = strRecipients
'### end all recipients addresses

'### Get the Exchange address
' if not using Exchange, this block can be removed
 Dim olEU As Outlook.ExchangeUser
 Dim oEDL As Outlook.ExchangeDistributionList
 Dim recip As Outlook.Recipient
 Set recip = Application.Session.CreateRecipient(strColB)

If InStr(1, strColB, "/") > 0 Then
' if exchange, get smtp address
    Select Case recip.AddressEntry.AddressEntryUserType
       Case OlAddressEntryUserType.olExchangeUserAddressEntry
         Set olEU = recip.AddressEntry.GetExchangeUser
         If Not (olEU Is Nothing) Then
             strColB = olEU.PrimarySmtpAddress
         End If
       Case OlAddressEntryUserType.olOutlookContactAddressEntry
         Set olEU = recip.AddressEntry.GetExchangeUser
         If Not (olEU Is Nothing) Then
            strColB = olEU.PrimarySmtpAddress
         End If
       Case OlAddressEntryUserType.olExchangeDistributionListAddressEntry
         Set oEDL = recip.AddressEntry.GetExchangeDistributionList
         If Not (oEDL Is Nothing) Then
            strColB = olEU.PrimarySmtpAddress
         End If
     End Select
End If
' ### End Exchange section

'write them in the excel sheet
  xlSheet.Range("A" & rCount) = strColA ' sender name
  xlSheet.Range("B" & rCount) = strColB ' sender address
  xlSheet.Range("C" & rCount) = strColC ' message body
  xlSheet.Range("D" & rCount) = strColD ' sent to
  xlSheet.Range("E" & rCount) = strColE ' recieved time
 
'Next row
  rCount = rCount + 1

' size the cells
    xlSheet.Columns("A:E").EntireColumn.AutoFit
    xlSheet.Columns("C:C").ColumnWidth = 100
    xlSheet.Columns("D:D").ColumnWidth = 30
    xlSheet.Range("A2").Select
    xlSheet.Columns("A:E").VerticalAlignment = xlTop

 Next
 xlApp.Visible = True

' to save but not close
'xlWB.Save

' to save and close
'     xlWB.Close 1
'     If bXStarted Then
'         xlApp.Quit
'     End If
' end save and close
   
     Set olItem = Nothing
     Set obj = Nothing
     Set currentExplorer = Nothing
     Set xlSheet = Nothing
     Set xlWB = Nothing
     Set xlApp = Nothing
 End Sub
Cách dùng:

1/ Chọn folder mail cần Export ra Excel
2/ Chọn tiếp những mail cần cần Export ra Excel
3/ Bấm phím alt + f8 rồi click chọn chạy sub: "CopyToExcel"

Chúc các bạn thành công !
@quick87 cảm ơn bạn đã chia sẽ một code rất hữu ích. Mình chỉ có một vấn đề nhỏ ở chỗ cột người nhận:
Đoạn code của bạn chạy rất tốt cho những email bên ngoài hệ thống công ty. Nhưng đối với email nội bộ nó chạy ra đoạn thông tin này: bạn có cách nào chỉnh lại code để nó xuất ra địa chỉ email nội bộ không:

"/o=ExchangeLabs/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=4a1d1b7ea9e0466d99e39bcbfa256955-Candy NGUYE; "

Dim strRecipients As String
Dim Recipient As Outlook.Recipient
For Each Recipient In olItem.Recipients
strRecipients = Recipient.Address & "; " & strRecipients
Next Recipient
example:

strColD = strRecipients
 
Web KT
Back
Top Bottom