Propósito

✔ Programação GLOBAL® - Quaisquer soluções e/ou desenvolvimento de aplicações pessoais, ou da empresa, que não constem neste Blog devem ser tratados como consultoria freelance. Queiram contatar-nos: brazilsalesforceeffectiveness@gmail.com | ESTE BLOG NÃO SE RESPONSABILIZA POR QUAISQUER DANOS PROVENIENTES DO USO DOS CÓDIGOS AQUI POSTADOS EM APLICAÇÕES PESSOAIS OU DE TERCEIROS.

VBA Outlook - Obtendo o endereço SMTP da um pasta pública do Exchange

Inline image 1

Blog Office VBA | Blog Excel | Blog Access |


Cada pasta na hierarquia do Exchange Server Public pode ter um endereço de e-mail. Caso saiba o endereço do SMTP, pode enviar mensagens, ou mesmo pedidos de reunião (Invites), diretamente desta pasta. 


O código abaixo mostra como obter o endereço da pasta usando a biblioteca Redemption para evitar o desencadeamento solicitado pela segurança do Outlook.

Também pode utilizar a mesma técnica com o objeto AddressEntry CDO, mas obviamente isso provocaria avisos de segurança em muitos ambientes (versões/instalações) do MS Outlook.

Use esta versão de código com uma biblioteca qualquer de 'Resgate' de terceiros (Por exemplo o SafeOutlookLibrary), para evitar os avisos de segurança geradas por tentativas de acesso aos objetos e as propriedades de endereço quando o Outlook E-mail Security Update estiver instalado.


Function R_GetPFAddress(objFolder)
    Dim oSafeFolder 'As New Redemption.MAPIFolder
    Dim objUtils 'As Redemption.MAPIUtils
    Dim arrBytes
    Dim strAddress, strEntryID 'As String
    Dim oAE 'As Redemption.AddressEntry

    Const PR_ADDRESS_BOOK_ENTRYID = & H663B0102
    Const PR_EMAIL = & H39FE001E

    On Error Resume Next

    Set objUtils = CreateObject ("Redemption.MAPIUtils")
    Set oSafeFolder = CreateObject ("Redemption.MAPIFolder")

    oSafeFolder.Item = objFolder
    arrBytes = oSafeFolder.Fields (PR_ADDRESS_BOOK_ENTRYID)
    strEntryID = objUtils.HrArrayToString (arrBytes)

    Set oAE = objUtils.GetAddressEntryFromID (strEntryID)

    R_GetPFAddress = oAE.Fields (PR_EMAIL)
 End Function


Reference:

TagsVBA, Outlook, SMTP, exchange, server, addressentry

VBA OutLook - Enviando lembretes por e-Mail.

Inline image 1

É verdade que haverão momentos nos quais desejará ser lembrado de coisas importante, como por exemplo, colocar alguma segurança ao seu redor.

Talvez possa fazer isso no MS Outlook, disparando um lembrete (remind). Também poderá enviar uma mensagem por e-mail.

O exemplo de código abaixo envia informações do Remind para o e-mail que especificarmos. 

Coloque esse código no módulo ThisOutlookSession.

Private Sub Application_Reminder(ByVal Item As Object)
  Dim objMsg As MailItem

  ' create new outgoing message
  Set objMsg = Application.CreateItem(olMailItem)

   ' your reminder notification address
  objMsg.To = "bernardess@gmail.com"
  objMsg.Subject = "Reminder: " & Item.Subject

  ' must handle all 4 types of items that can generate reminders

  Select Case Item.Class

     Case olAppointment '26
        objMsg.Body = _
          "Start: " & Item.Start & vbCrLf & _
          "End: " & Item.End & vbCrLf & _
          "Location: " & Item.Location & vbCrLf & _
          "Details: " & vbCrLf & Item.Body

     Case olContact '40
        objMsg.Body = _
          "Contact: " & Item.FullName & vbCrLf & _
          "Phone: " & Item.BusinessTelephoneNumber & vbCrLf & _
          "Contact Details: " & vbCrLf & Item.Body

      Case olMail '43
        objMsg.Body = _
          "Due: " & Item.FlagDueBy & vbCrLf & _
          "Details: " & vbCrLf & Item.Body

      Case olTask '48
        objMsg.Body = _
          "Start: " & Item.StartDate & vbCrLf & _
          "End: " & Item.DueDate & vbCrLf & _
          "Details: " & vbCrLf & Item.Body
  End Select

  ' send the message 
  objMsg.Send
  Set objMsg = Nothing
End Sub

Reference:
Inspiration:

TagsVBA, Outlook, send, reminder, email, lembrete

VBA Excel - Automatizando anotações recorrentes - Automate recurring appointments on MS Outlook

Inline image 1

Este código serve para automatizarmos certas anotações que desejamos fiquem registradas para nossas lembranças posteriores. Isso pode ser feito dentro do MS Outlook, mas também pode ser executado fora dele em outras instancias.


Let strExcelPath = ""

Const olAppointmentItem = 1
Const olRecursWeekly = 1

Set objExcel = CreateObject("Excel.Application") 

objExcel.WorkBooks.Open strExcelPath

Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)

Let intRow = 3

Do While objSheet.Cells(intRow, 1).Value <> ""
    Let strName = objSheet.Cells(intRow, 3).Value
    Let strDate = objSheet.Cells(intRow, 4).Value
    
    Set objOutlook = CreateObject("Outlook.Application")
    Set objAppointment = objOutlook.CreateItem(olAppointmentItem)

    Let strStart = strDate & "/2013 11:00 AM"
    Let strEnd = strDate & "/2099 11:00 AM"
    Let objAppointment.Start = strStart
    Let objAppointment.Duration = 30
    Let objAppointment.Subject = strName & " Event"
    Let objAppointment.Body = "Lembre-se, hoje você tem compromisso com " &strName& "' - Reunião de ..."
    Let objAppointment.Location = "Triumph Circle"
    Let objAppointment.ReminderMinutesBeforeStart = 15
    Let objAppointment.ReminderSet = True

    Set objRecurrence = objAppointment.GetRecurrencePattern
    Let objRecurrence.RecurrenceType = 5
    Let objRecurrence.PatternStartDate = strStart
    Let objRecurrence.PatternEndDate = strEnd

    objAppointment.Save
    
    Set objRecurrence = nothing
    Set objAppointment = nothing
    Set objOutlook = nothing
  
    Let intRow = intRow + 1
Loop

' Close workbook and quit Excel.
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit

set objSheet = nothing
set objExcel = nothing

Reference:

Aditya Kalra

Inspiration:
André Luiz Bernardes

TagsVBA, Excel, Outlook, automation, automate, appointment, 

VBA Excel - Convertendo planilha Excel para arquivo texto - Convert Excel to Text file

Inline image 1

Parece não haver por aí muitos códigos que demonstram como converter o conteúdo de planilhas em arquivos texto. Pelo menos não de forma reutilizável. Espero que este possa ajudar a muitos, especialmente os neófitos.

'Prompts for accepting user input
Let strViewPath = Trim (InputBox ("PLANILHA - Por favor, digite o path do arquivo",,"C:\Bernardes\"))
Let strTest = Trim (InputBox ("TEXTO - Por favor, digite o arquivo texo",,"sample"))
       
If Right (strViewPath, 1) <> "\" Then
   Let strViewPath = strViewPath & "\"   
End If       

Let strTestName = strTest
Let strTextFilePath = strViewPath
   
'Assign the values for the excel and text file that needs to be converted
Let TestToConvert = strViewPath + strTest + ".xls"
Let TextFile =strTextFilePath  + strTestName + ".txt"
   
'Create the excel object
Set oExcel = CreateObject("Excel.Application")
Let oExcel.Visible = False

'Open the excel file for conversion
Let oExcel.DisplayAlerts = False
oExcel.Workbooks.Open TestToConvert, True
'Call the text streamer function that will convert the file
TextStreamer TextFile, oExcel
'Exit the Excel file
oExcel.Quit

Private Sub TextStreamer(TextFileName, objExcel)

'Declare constants for reading,writing and appending to a text file
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
   
Dim fs, f, ts, x, y, LastRow, LastColumn, c, objSheet, shts()
'Create the file system object for text file editing
Set fs = CreateObject("Scripting.FileSystemObject")
fs.CreateTextFile TextFileName
       
Set f = fs.GetFile(TextFileName)
Set ts = f.OpenAsTextStream(ForWriting, TristateUseDefault)
   
'Get the number of worksheets in the source excel file
Let intNoOfSheets = objExcel.Worksheets.count
Let z = intNoOfSheets
   
'Traverse through every sheet that needs to be converted
For i = 1 to intNoOfSheets
       
 'Activate the first worksheet
    objExcel.Worksheets(z).Activate
    objExcel.Worksheets(z).Select
    Set objSheet = objExcel.ActiveWorkbook.Worksheets(z)
    
    Let strSheetName = objsheet.name
    objSheet.Cells(1).Select

    Let LastRow = objSheet.UsedRange.Rows.Count + 2
    Let LastColumn = objSheet.UsedRange.Columns.Count   
                   
    objSheet.Cells(1).Select
                   
    ts.write "["&strSheetName&"]"
    ts.write Chr(13) & Chr(10)
           
    'Loop through the rows and columns in the excel worksheet and write the data to the text file       

    For x = 0 To LastRow
        For y = 0 To LastColumn -1
            If objExcel.ActiveCell.Offset(x, y).Value <> "" then
                ts.write (objExcel.ActiveCell.Offset(x, y).Value)
                'ts.write Chr(9)   
            End If
        Next
        ts.write Chr(13) & Chr(10)
    Next               
  
Let z= z-1

Next
       
'Close the excel file test streamer
ts.Close
msgbox "Conversion Complete!"
End Sub

Reference:
Aditya Kalra
Inspiration:

TagsVBA, Excel, convert, text, to text, planilha, sheet, worksheet, 

VBA Excel - Juntando distintas planilhas - Combine worksheets in Excel and Kill all excel objects

Inline image 1

Quando estamos trabalhando com várias planilhas, não raramente centenas delas, e precisamos elaborar uma análise, um relatório, importá-las para uma base de dados, etc...Tudo isso seria mais fácil se ao invés de termos centenas de arquivos, tivéssemos acesso a somente uma planilha contendo os dados de todas as demais. Sim, meus caros, nos pouparia muito tempo. E como sempre nos vem a pergunta: Como?

Segue:

Sub CopyFromWorksheets()
Dim wrk As Workbook
Dim sht As Worksheet
Dim trg As Worksheet
Dim rng As Range
Dim colCount As Long
'Dim sheetDelimiter As String
' Creates excel app object
Set objExcel = CreateObject("Excel.Application")
   
' Makes the excel invisible
objExcel.Visible = False
' Supress all display alerts
objExcel.DisplayAlerts = False
' Gets the complete path of the active excel sheet
strExcelFilePath = ActiveWorkbook.FullName
  
' Opens the excel file
Set objWorkbook = objExcel.Workbooks.Open(Trim(strExcelFilePath))

Set objWorkSheet = objWorkbook.Worksheets("Merge")
objWorkSheet.Activate
' Gets the count of column
Set objRange = objWorkbook.Worksheets("Merge")
numRowsCount = objRange.Evaluate("COUNTA(A1:A100)")
Worksheets("Merge").Activate
'sheetDelimiter = "######"
Set wrk = ActiveWorkbook 'Working in active workbook
For Each sht In wrk.Worksheets
If sht.Name = "Consolidated Backlog" Then
MsgBox "There is a worksheet called as 'Consolidated Backlog'." & vbCrLf & _
"Please remove or rename this worksheet since 'Consolidated Backlog' would be" & _
"the name of the result worksheet of this process.", vbOKOnly + vbExclamation, "Error"
Exit Sub
End If
Next sht
Application.ScreenUpdating = False
Set trg = wrk.Worksheets.Add(After:=wrk.Worksheets(wrk.Worksheets.Count))
trg.Name = "Consolidated Backlog"
'Get column headers from the first worksheet
'Column count first
Set sht = wrk.Worksheets(1)
colCount = 30

For cntLoop = 1 To numRowsCount
     strSheetName = Trim(UCase(objExcel.Cells(cntLoop, 1).Value))
     If Trim(strSheetName) = "" Then
        Exit For
     End If
     If Trim(strSheetName) = "SHEET NAMES" Then
       GoTo Continue
     End If
     For Each sht In wrk.Worksheets
        'If worksheet in loop is the last one, stop execution (it is Master worksheet)
        If sht.Index = wrk.Worksheets.Count Then Exit For
        If strSheetName = UCase(sht.Name) Then
            'Delimits the copied sheets with a string in a new row
            With trg.Cells(1, 1).Resize(1, colCount)
                .Value = sht.Cells(1, 1).Resize(1, colCount).Value
                 'Set font as bold
                .Font.Bold = True
            End With
            
            trg.Cells(Rows.Count, 1).End(xlUp).Offset(1).Resize(1, 1).Value = sheetDelimiter
            Set rng = sht.Range(sht.Cells(2, 1), sht.Cells(Rows.Count, 1).End(xlUp).Resize(, colCount))
            rng.Copy trg.Cells(Rows.Count, 1).End(xlUp).Offset(1)
            'Set objRange = sht.Range("A1").EntireColumn
            'objRange.Insert (xlShiftToRight)
            'sht.Range("A1") = sht.Name
        End If
    Next sht
Continue:
Next
objExcel.Quit
Set objWorkbook = Nothing
Set objExcel = Nothing
Set sht = Nothing
Set objWorkSheet = Nothing
Set objRange = Nothing
Set trg = Nothing
Set rng = Nothing
Application.ScreenUpdating = True
'create WMI object instance
Set objWMI = GetObject("winmgmts:")
If Not IsNull(objWMI) Then
'create object collection of Win32 processes
Set objProcList = objWMI.InstancesOf("win32_process")
For Each objProc In objProcList 'iterate through enumerated
If UCase(objProc.Name) = UCase(procName) Then
objProc.Terminate (0)
End If
Next
End If
Set objProcList = Nothing
Set objWMI = Nothing

End Sub

Reference:

Aditya Kalra

Inspiration:
André Luiz Bernardes

TagsVBA, Tips, dummy, dummies, row, last, cell, célula, dirty area, detect, detectar

diHITT - Notícias