Getting current contact name/address from Address Book

Hello there

Still learning the vocab/grammar of the AS language, I can’t figure out how to do something I reckon should be pretty simple: with the Address Book open at a particular contact, I want a script that takes name and address, jiggles the formatting a bit (that part is easy) and sticks the result in the clipboard, so I can paste it into a letterhead.

I can’t for the life of me figure out how first of all to get access to the current contact’s firrst name, last name, and address fields - once I know how to do that, I can get them into local variable and play with the formatting.

Any suggestions? Maybe it would be easier to do an AB search (I’ve seen a couple of good script examples on the BBS for doing this) and then grab the data from the resultant record, than to try getting it from current contact? I’m at sea here.

  • padmavyuha

Even veteran AppleScripters feel that way sometimes. Welcome to the club :slight_smile:

My guess is you’re doing something like:

tell application "Address Book"
	set currentPerson to selection
	set theirName to name of currentPerson
end tell

and it doesn’t work, right?

That’s because ‘selection’ doesn’t return a single contact, it returns a list of people (since you could have more than one person selected) and you can’t get ‘name’ of a list.

Instead, you need to extract the person record out of the list first. There’s a couple of ways of doing this. The easiest is to simply work on the first item in the list.:

tell application "Address Book"
	set currentPerson to first item of (get selection)
	set theirName to name of currentPerson
end tell

Now you ‘get selection’ which returns a list, then you set the variable ‘currentPerson’ to the first item in that list. This does mean that if you have multiple people selected the script may not do what you expect.

Well, I tried

tell application "Address Book" 
    set currentPerson to first item of (get selection) 
    set theirName to name of currentPerson 
 end tell

but though it passed the syntax test, I got an NSCannotCreateScriptCommandError, with the word ‘selection’ in the script highlighted.

What’s that??

  • padmavyuha

The code works fine for me here on 10.3.1.

Which OS version are you running?

10.2.8 (the director’s cut…)

  • padmavyuha