Search code examples
vbaexcelstring-concatenation

Write value to text file, not name of object


I have some code which works great if putting the values into an Excel sheet but when I have tried to make it write to a text file it just writes the following over and over again:

objAddressEntry.Name

objAddressEntry.Name

Code below. I've left in the bit that originally wrote to Excel but it's commented out.

Sub GetOutlookAddressBook()

' Need to add reference to Outlook
'(In VBA editor Tools References MS Outlook #.# Library)
' Adds addresses to existing Sheet called Address and
' defines name Addresses containing this list
' For use with data Validation ListBox (Source as =Addresses)

On Error GoTo error

Dim objOutlook As Outlook.Application
Dim objAddressList As Outlook.AddressList
Dim objAddressEntry As Outlook.AddressEntry
Dim intCounter As Integer

Application.ScreenUpdating = False

' Setup connection to Outlook application
Set objOutlook = CreateObject("Outlook.Application")
Set objAddressList = objOutlook.Session.AddressLists("Global Address List")

Application.EnableEvents = False

' Clear existing list
' Sheets("Address").Range("A:A").Clear

' Create text file
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = fso.CreateTextFile("C:\Users\username\Desktop\test.txt")

'Step through each contact and list each that has an email address
For Each objAddressEntry In objAddressList.AddressEntries
If objAddressEntry.Address <> "" Then
intCounter = intCounter + 1
Application.StatusBar = "Address no. " & intCounter & " ... " & objAddressEntry.Address

' Write to text file
oFile.WriteLine "objAddressEntry.Name" & vbNewLine

' Sheets("Address").Cells(intCounter, 1) = objAddressEntry.Name
DoEvents
End If
Next objAddressEntry

' Close the text file
oFile.Close
Set fso = Nothing
Set oFile = Nothing

' Define range called "Addresses" to the list of emails
' Sheets("Address").Cells(1, 1).Resize(intCounter, 1).Name = "Addresses"
error:
Set objOutlook = Nothing
Application.StatusBar = False
Application.EnableEvents = False
End Sub

Note that I rarely use VBA so I apologise if this is a trivial issue. I have struggled to find anything relevant in previous questions/answers as the search terms are quite broad.

My question is: How do I make it write the actual value rather than the name of the object?


Solution

  • If you just want to write the .Name then,

    oFile.WriteLine objAddressEntry.Name & vbNewLine
    

    ... but if you want to write the .Name in quotes then,

    oFile.WriteLine chr(34) & objAddressEntry.Name & chr(34) & vbNewLine