将值写入文本文件,而不是对象的名称

时间:2018-02-23 15:15:16

标签: excel vba excel-vba string-concatenation

我有一些代码,如果将值放入Excel工作表中,但是当我尝试将其写入文本文件时,它只会反复写入以下代码:

objAddressEntry.Name

objAddressEntry.Name

以下代码。我已经离开了最初写入Excel的位,但它被注释掉了。

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

请注意,我很少使用VBA,所以如果这是一个微不足道的问题我会道歉。我一直在努力寻找与之前的问题/答案相关的任何内容,因为搜索条件相当广泛。

  

我的问题是:如何让它写出实际值而不是对象的名称?

1 个答案:

答案 0 :(得分:1)

如果你只想写.Name,那么

oFile.WriteLine objAddressEntry.Name & vbNewLine

...但如果你想在引号中写.Name,

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