View Single Post
 
Old 03-15-2024, 07:21 AM
Trio78 Trio78 is offline Windows 11 Office 2021
Novice
 
Join Date: Mar 2024
Posts: 3
Trio78 is on a distinguished road
Default Outlook VBA macro runs from editor, but not from Outlook ribbon?

I have a macro I made to create a new directory and move the selected message into it. It works fine if I run it from the VBA editor, but when I try to run it from Outlook using a button on the ribbon, nothing happens.

I have Macro Security set to "Enable all macros", at least for testing.

Code:
Sub MakeNewPIFolderAndMoveEmail()
    Dim objOutlook As Outlook.Application
    Dim myItems As Outlook.Items
    Dim fldRoot As Outlook.MAPIFolder
    Dim fldPIs As Outlook.MAPIFolder, fldNew As Outlook.MAPIFolder
    Dim strFolderName As String
    Dim Explorer
    Dim CurrentItem
        
    Set objOutlook = CreateObject("outlook.application")

    ' from the default inbox to the parent which is your mailbox
    Set fldRoot = objOutlook.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Parent
    ' from the mailbox to a folder at the same level as the Inbox
    Set fldPIs = fldRoot.Folders("PIs")

    strFolderName = InputBox("Enter name for the PI folder", "Folder Name")
    
    If Len(strFolderName) = 0 Then
      Exit Sub
    End If
    
    Set fldNew = fldPIs.Folders.Add(strFolderName)
    Set Explorer = Application.ActiveExplorer
 
    ' Check whether any item is selected in the current folder.
    If Explorer.Selection.Count Then
 
      ' Get the first selected item.
      Set CurrentItem = Explorer.Selection(1)
      If CurrentItem.Class = olMail Then
        CurrentItem.Move fldNew
      End If
    End If
End Sub
Reply With Quote