Is it possible to message another computers on a network via Excel VBA?
Example: If I save a shared Excel file on a network, it will send a message to other shared users whether they are using that shared file or not.
To send a message to other computers on the network (DOS window):
1.
msg /Server:serverName * /Time:5 "Message text..."
msg /Server:192.168.1.1 "Message text..."
Details (from Microsoft):
msg
{UserName|SessionName|SessionID|#FileName|*}
[/server:ServerName]
[/time:Seconds]
[/v]
[/w]
[Message]
2.
net send 192.168.0.1 "Message text..."
Details:
net send {name | * | /domain[:name] | /users} message
.
From VBA you can use something like this:
Dim result As Long
result = CreateObject("WScript.Shell").Run("msg /Server:192.168.1.1 'Message text...'")
Or this:
Shell("msg /Server:192.168.1.1 'Message text...'", vbNormalFocus)
.
PS. A shared file cannot send a message if it's inactive, but you can implement a VBA procedure that will automatically send a message to a list of named computers (or IP addresses) when someone opens the file (Workbook_Open() event of ThisWorkbook module) or when they access / edit certain cells on a sheet
The Excel VBA they may be running is running on their computers, you may not open the same files unless they are shared (even if shared I don't know how the variables stored in VBE are behaving).
Shared spreadsheets can be used to store variables, e.g. timestamps and userIDs (by the above description: in cells). You can have macros saved in them before sharing them that would check the variables and notify if something relevant ha happened.
Alternatively you can spam them all with emails from Excel to Outlook VBA.
Related
I need to write the contents of a listbox to a textfile which then gets added as an attachment to an email. all of this works, but only once. if i try to send it, then edit the email address it sends to, then try to rewrite and send the file it gives me this error. "the process cannot access the file because it is being used by another process".
ReceiptWriter = IO.File.CreateText(filelocation)
For i = 0 To Me.lstRecieptBox.Items.Count - 1
Me.lstRecieptBox.SetSelected(i, True)
ReceiptWriter.WriteLine(Me.lstRecieptBox.SelectedItem)
Next
ReceiptWriter.WriteLine("-------------------")
ReceiptWriter.Close()
I want to be able to write the information to the file and then be able to edit the email address it sends to, and it be able to write over that file and send it again.
I want to;
Search the Global Address List of MS Outlook
Using an input, filterStr
To retrieve all items asynchronously that match a criteria satisfying
Contact first name starts with filterStr or contact last name starts with filterStr
Display the contacts as they become available in some sort of list
I am developing a MS Outlook add-in with Visual Studio 2017 using VB.net. (c# code examples are wellcome). I need this add-in to be able to search contacts like MS Skype for Business does, through its "Find Someone" field of "RICHEDIT60W"
I have tried the following so far;
Use "RICHEDIT60W" of MS Skype for Business (the search field) in my form
Could not find documentation
Use the "RichEdit20WPT" of MS Outlook (the "TO:" field in new e-mail compose)
Could not find documentation
Get the "Global Address List" through Session.GetGlobalAddressList
Succeeded, but looping through more than 50k items is too slow
Use the System.DirectorySearcher
This does not always work. When I'm connected to my corporate network through cable, I can create the object. When I'm connected through my home wireless, I get the error: "specified domain does not exist or could not be contacted"
I did try using a DirectoryEntry object initialized with;
name.surname.corporation.com where my e-mail address is name.surname#corporation.com, this time I get an "unspecified error"
I tried using ADODB to connect as given in https://learn.microsoft.com/en-us/windows/desktop/ad/example-code-for-searching-for-users#visual-basic-example
This also gives me an error on line 42 (root = GetObject("LDAP://rootDSE")
QUESTION: How can I do any of the following;
Get DirectorySearcher to work
Get ADODB method to work
Use the existing RichEdit controls of either Outlook or Skype for Business
?
I solved it like this;
Getting the GAL itself and the AddressEntries is fast enough, no problem there
I'm looping through the AddressEntries only once, during initialization and getting only the Nameproperties of each to a List(Of String), which takes around 3 seconds
When I need to search for an entry, I'm using Linq to query the list with IndexOf function, which takes about 150ms max to get all matches, and the items of the list are immediately accessible
This suited my needs because
- It works through my home network and even when I don't have a connection (I assume Outlook is cacheing the GAL)
- Querying using Linq is fast enough to facilitate searching as the user types
On the low (Extended MAPI - C++ or Delphi only) level, you would need to apply PR_ANR MAPI restriction: that is what Outlook uses when it resolves a name and displays the list of ambiguous matches. You can run that code on a separate thread, but it won't return matches one at a time - you will get the whole set back.
If Extended MAPI is not an option, you can use Redemption (I am its author) and its RDOSession.AddressBook.GAL.ResolveNamesEx method:
set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT
set AdrrEntries = Session.AddressBook.GAL.ResolveNameEx("John")
Debug.Print AdrrEntries.Count & " names were returned by ResolveNameEx:"
Debug.Print "------------"
for each AE in AdrrEntries
Debug.Print AE.Name
next
Debug.Print "------------"
I receive emails with subjects of the form “### auto fax” where “###” is a variable number of digits. Each of these emails must be forwarded to “####mail2fax.com”. I am looking for ideas on how to automate this.
Your addition “and it needs me to be at office” may be a problem. I am a home user of Outlook. If I want Outlook to do any while I am away, I need to leave my computer switched on. I assume you are an Outlook Exchange user. You can leave instructions that will be obeyed while you are away even if your computer is switched. However, for security reasons, the default is that you cannot leave instructions to forward an email outside your company. As I understand it, you would need to forward the “Auto fax” emails to a colleague. Since we hope to automate the process, this should not be an imposition on your colleague. You would need to create a version of your rule and macro and install it on your colleague’s computer but this should not be too difficult if my reading of this functionality is correct. The point is, that this will not be part of this answer.
A difficulty with VBA is that there are usually several ways of achieving the same effect. This does not matter if you develop your own VBA; pick your favourite way of achieving an effect and experiment until you have a full understanding of that favourite. However, if you ask for help or look for useful snippets of code, you must have a basic familiarity with every way of achieving effects because others will not share your favourite. You may find you have to get the idea of what a snippet does and then rewrite it your way. This code is written using my favourite techniques.
When you write a macro to process emails, you have two issues:
How do you select the emails you wish to process?
How do you process the selected emails?
There are four methods of selecting emails:
The user selects one or more emails and then runs the processing macro.
The macro scans one or more folders looking for emails with particular characteristics and then processes them.
You instruct Outlook to monitor a particular folder and to run a macro every time a new email arrives in that folder.
You set up a rule to select emails as the arrive and link a macro to that rule to process them.
I believe method 4 will be the easiest method to implement your requirement. However, it may not be available. It works fine on my system but apparently those responsible for an Outlook Exchange installation can forbidden it. If method 4 does not work for you, I believe method 3 will be the next best method. However, this answer will use method 1.
I use method 1 whenever I am developing a new email processing macro. If gives me total control of which emails are processed in which order. I can start with simple emails and I can run the macro against the same email again and again until I get the macro working just the way I want. Once I am satisfied with the macro, I can switch to whichever of the other methods is most appropriate.
This is the first version of my processing macro:
Public Sub ForwardAndMoveEmail(ByRef ItemCrnt As Object)
Dim FaxNum As String
Dim ItemNew As MailItem
Dim Subject As String
If ItemCrnt.Class <> olMail Then
' Ignore item if it is not an email
Exit Sub
End If
Subject = ItemCrnt.Subject
If LCase(Right$(Subject, 9)) = " auto fax" Then
‘ Only process email if the subject ends with case-insensitive " auto fax"
FaxNum = Mid$(Subject, 1, Len(Subject) - 9)
With ItemCrnt
Subject = "Fax from " & .Sender & " (" & .SenderEmailAddress & ")"
Set ItemNew = .Forward
End With
With ItemNew
.Subject = Subject
' Clear existing recipient(s)
Do While .Recipients.Count > 0
.Recipients.Remove (1)
Loop
.Recipients.Add FaxNum & "#mail2fax.com"
.Save
End With
End If
ItemCrnt.Move ItemCrnt.Parent.Parent.Folders("Faxed")
End Sub
The item to be processed is a parameter to this macro. Note that I have typed it as an Object rather than as a MailItem. Then note that the first statements of the macro checks that the item is a MailItem (Class = olMail). With method 1, the user could select something other than a MailItem. This check ensures this user error causes no problem for the macro.
Next the macro checks the Subject ends in “ auto fax” or “ Auto fax” or “ AUTO FAX” or any other variation. With method 1, the user could select the wrong MailItem. With method 3, every email is passed to the macro. Hence, the check that it is a macro to be forwarded to the fax service.
If I decided in advance which selection method I was going to use, I would not need to perform all these checks. I think that being able to change the selection method is worth the extra checks.
The macro extracts the leading characters of the Subject. I do not check that they are numeric although such a check could be added if it was important.
The macro creates a new Subject for the forwarded email. I do not know if you would want a new Subject but this demonstrates what you can do if it was helpful.
Set ItemNew = .Forward creates the item to be forwarded. Note that this statement is within a With block. This is the same as Set ItemNew = ItemCrnt.Forward.
The macro then works on ItemNew. It changes the Subject, it clears the existing recipients and adds the new one and then saves the new email as a draft.
The last statement of the macro is something else you did not ask for but which may be useful. I have created a folder named “Faxed” and I move the original email to it. This saves the original email without cluttering your Inbox.
Consider ItemCrnt.Parent.Parent.Folders("Faxed"). This is the folder to which the item is to be moved. I have chained properties together in a way that probably looks strange but is straightforward once you understand it.
ItemCrnt is the original mail item.
ItemCrnt.Parent is a property of ItemCrnt. Many objects have parents. For a MailItem it is the folder holding the MailItem; that is, folder “Inbox”.
`ItemCrnt.Parent.Parent is a property of folder “Inbox”. For a folder, its parent is the folder containing it. Since folder “Inbox” is a top-level folder, its parent is the store holding it. A “store” is a file in which Outlook stores folders, mail items, calendar items, tasks and many other things.
Having gone all the way up to the store, ItemCrnt.Parent.Parent.Folders("Faxed") goes down to a folder within the store.
The macro that calls ForwardAndMoveEmail is:
Option Explicit
Sub SelectEmailsUser()
Dim Exp As Explorer
Dim ItemCrnt As Object
Dim MailItemCrnt As Object
Set Exp = Outlook.Application.ActiveExplorer
If Exp.Selection.Count = 0 Then
Call MsgBox("Please select one or more emails then try again", vbOKOnly)
Exit Sub
End If
For Each ItemCrnt In Exp.Selection
If ItemCrnt.Class = olMail Then
Call ForwardAndMoveEmail(ItemCrnt)
End If
Next
End Sub
Don’t worry too much about this macro at this stage. Study it later when you are ready to develop your next processing email. It is a macro I wrote a long time ago. Each time I want to test a new email processing macro I simply change statement Call ForwardAndMoveEmail(ItemCrnt) to call the new macro.
This is not the final version of the processing macro although it is probably the final version of this evening. Please:
Copy the two macros to an Outlook module. The two macros can be in either order but Option Explicit must be at the top of the module.
Create folder “Faxed”. At the same level as folder “Inbox”.
Select one or more of the “Auto fax” emails and run macro SelectEmailsUser.
Check the processed “Auto fax” emails are now in folder “Faxed”.
Review the emails in folder Drafts. I think these emails are unsatisfactory. I will tell why later and what I think you should do to make them satisfactory.
Part 2
I ended the first part of this answer by saying I did not think the draft email my macro had created was satisfactory.
The problem for me is that the original email is headed up by a typical “forwarded” header: original sender, my name, date sent and subject. The author of the email has presumably spent some time creating the text of the email and would not want this irrelevant header prefixing their text. So how was I to stop this header being included in the email sent to “mail2fax.com”?
My first idea was to use method “Copy” instead of method “Forward”. This did give a satisfactory appearance but was slight awkward. With the statement Set ItemNew = ItemCrnt.Forward, ItemNew is a draft email ready to be finished and saved in folder “Drafts” or sent. But with the statement Set ItemNew = ItemCrnt.Copy, ItemNew is a received email and, when saved, is placed in folder “Inbox”. I have sent a copied email and the appearance when it arrives at one of my secondary email addresses looks satisfactory.
My second idea needs an introduction. An email can have three bodies: plain text, HTML or RTF. I have never seen an email containing a RTF (Rich Text Format) body. RTF was probably a sensible format 20 years ago if you wanted more that plain text. But today, HTML is so powerful that the same email can be rearranged for a large PC screen, a tablet or a smart phone so it is always easy to read. So for all practical purposes there are only two formats for an email: plain text and HTML. If an email has both plain text and HTML bodies, it is the HTML body that is shown to the reader. The VBA programmer can look at either or both bodies but the reader is not told that there is a plain text body. Very occasionally, I have seen a carefully constructed plain text body that has been designed for an email package that cannot handle HTML. But normally the plain text body is just the HTML body with the HTML tags stripped out.
My second idea was to use method “Forward” but then to copy the text and HTML bodies from the original email.
In the above code, you will find:
.Subject = Subject
' Clear existing recipient(s)
Please replace these two lines with:
.Subject = Subject
.Body = ItemCrnt.Body
.HtmlBody = ItemCrnt.HtmlBody
' Clear existing recipients
With this change, the draft emails will not have a “forwarded” header.
I assume you know who these emails are being faxed to. I suggest you contact one or two and say you are going to conduct an experiment. They will have already received faxes as a result of you using the keyboard interface to forward these emails. Send some of the draft emails created by my macro and ask for the recipients’ opinion on the new appearance. If they prefer the new appearance, we will be ready to move on to stage 3: Automating these emails. If they do not like the new appearance, you will need to ask them what is wrong about the new appearance and we will have to attempt to fix the problem.
Part 3
Please do not follow the instructions in this part until you are convinced that emails created by macro ForwardAndMoveEmail are as they should be. This part is about automating the process so the emails will be sent without you having any opportunity to check or correct them before they are sent.
Please make the following changes to macro ForwardAndMoveEmail:
Replace Public Sub ForwardAndMoveEmail(ByRef ItemCrnt As Object)
by Public Sub ForwardAndMoveEmail(ByRef ItemCrnt As MailItem).
With email selection method 1, it is possible (difficult but possible) to select items that are not MailItemss. I set the type of ItemCrnt to Object so this would not cause an error. To use a macro with a rule, ItemCrnt must be MailItem.
These statements are now redundant:
If ItemCrnt.Class <> olMail Then
' Ignore item if it is not an email
Exit Sub
End If
You can leave these statements since they will do no harm. Alternatively, you could delete them or place a quote in front of each statement.
Replace .Save by .Send.
On my system I can attach a macro to a rule. If you can do the same, it will be the easiest approach. However, some IT departments consider attaching a macro to a rule to be a security risk and disable it. If you find you cannot attach a macro to a rule, you will have to try the event approach. I will add additional instructions if necessary.
The screenshots below are from my home Outlook installation. You have functionality I lack so the screens you see will not be identical. However, my screenshots should be similar enough to yours to be useful.
Select one of these “auto fax” emails. From the “Home” tab click “Rules” then “Create Rule...”. You will get a pop-up window like this:
I created an “Auto fax” email in one of my secondary accounts and sent it to me main account. This is why I am shown as both the sender and the receiver. Because I had selected the “Auto fax” email, its subject is shown. Edit this subject to remove the leading digits. A tick will appear in the box next to the subject to get:
Click “Advanced Options...” to get this pop-up window:
Notice that subject in the line near the top has not been edited. This does not matter; it is the value in the “Step 2” box that matters. Note that if you click “ Auto fax” in the “Step 2” box, you can add extra values. So if some of these emails have slightly different subjects, you can add these alternative values. Click “Next” to get a pop-up window like this:
Near the bottom is “Run a script”. You will have more options and may have to scroll down to see this option. Click the box next to this option. “Run a script” will appear in the “Step 2” box. Click “Run a script” in the “Step 2” box. You will be asked to “Enable macros” if you have not done so already. A new pop-up window will appear showing all the macros that could be selected for this option. I have several possible macros so I will not show you my list. You should only see one macro: ForwardAndMoveEmail. To appear in this list, a macro must be Public and the first parameter must be a MailItem. Select ForwardAndMoveEmail if it isn’t selected and click “OK”. “Run a script” now reads “Run ForwardAndMoveEmail”. Click “Next”. You will get a pop-up window of exceptions which I assume are irrelevant to you. Click “Next” to get the final pop-up:
You can click the box against ‘Run this rule now on messages already in “Inbox”’ to forward any of “Auto fax” emails already received but not forwarded. Click “Finish”.
The “Auto fax” rule is now operational and any “Auto fax” emails will be forwarded automatically. It would be a good idea to monitor folder “Faxed” and check the intended recipients received their faxes.
I have the following basic Send Object Macro.
Function McrSnapshotCallData()
On Error GoTo McrSnapshotCallData_Err
DoCmd.SendObject acQuery, "Qry_SnapShot", "Excel97-Excel2003Workbook(*.xls)", "xxx#xxx.com", "", "", "Calls", "Please find attached", False, ""
McrSnapshotCallData_Exit:
Exit Function
McrSnapshotCallData_Err:
MsgBox Error$
Resume McrSnapshotCallData_Exit
End Function
I need to be able to send run this macro on a server using a scheduler enabling an email to be sent out.
Currently this requires and outlook account on the server and it does not have one. Is it possible to include SMTP server details so this can be run automatically without me having to log on every night and send this.
Please can you me help adjust this if possible.
Sorry I am not very good with VBA stuff. Thanks
I can recommend these tools:
Blat: http://www.blat.net/ (free)
Blat is a Windows (32 & 64 bit) command line utility that sends eMail using SMTP.
Chilkat ActiveX libraries: http://www.chilkatsoft.com/email-features.asp (not free, but a lot more options)
MailMan: The Chilkat MailMan class is reponsible for sending email though SMTP and receiving/managing email on POP3 servers.
Email: Represents a complete Email object.
In both cases you'd first save the query as xls (DoCmd.TransferSpreadsheet) and then mail that file.
I have two mailbox accounts in Outlook 2010.
Primary: Bob#something.com
Secondary: help#something.com
Every time I receive new mail to help#something.com I get the envelope of new mail.
I want to receive the envelope only for Bob#something.com
I cancelled the option to receive envelopes in Outlook.
I created a rule in Outlook 2010 under the account of Bob#something.com
I have the option to run a script but its empty.
I need to write VBA code that can do it:
If (mail was send to Bob#something.com) Then
show Envelope
End If
I know that I can just add the folder of help#something.com instead of its account but it is not possible in my environment (cloud users).
I searched on the web and didn't find anything like this. For example, I did not find what code line can turn the envelope on in Windows.
If you find displaying a message box is an acceptable alternative then the Run a Script format is described here Outlook's Rules and Alerts: Run a Script
From the rule you pass the new mail as "Item" like this:
Public Sub DisplayMessageBox(Item As Outlook.MailItem)
' You need not do anything with "Item" just use it as a trigger
MsgBox "New mail in Bob#something.com"
' or you can enhance the message using "Item" properties
MsgBox "New mail in Bob#something.com - Subject: " & Item.Subject
End Sub
You may also consider ItemAdd or NewMailEx which are a little more complex.
There is an ItemAdd example here How do I trigger a macro to run after a new mail is received in Outlook?