повторение сценария, перебирающего диапазон переменных

Я почти ничего не знаю о написании сценариев для Apple и был бы признателен за вашу помощь! Вот что я пытаюсь сделать:

Напишите сценарий, который копирует и вставляет ячейку Excel в слово, а затем автоматически сохраняет файл в формате PDF. Затем сценарий автоматизирует почтовую программу Apple для отправки набора электронных писем (с вложениями) на основе электронной таблицы Excel.

До сих пор я написал сценарий, который делает все это, за исключением того, что у меня возникли проблемы с повторением сценария со следующей ячейкой и так далее, пока все ячейки и электронные письма не будут выполнены. Вот что у меня есть до сих пор:

tell application "Microsoft Excel"
activate
set empName to string value of range "A4" of active sheet
set myVal to string value of range "P4" of active sheet
tell application "Finder"
    set theFile to "Macintosh HD:users:deve:desktop:C.dotx"
    tell application "Finder"
        open file theFile
        set the clipboard to myVal
        tell application "Microsoft Word"
            activate
            tell application "System Events"
                tell application process "Microsoft Word"
                    keystroke "v" using command down
                    keystroke "a" using command down
                    tell application "font" - this is just so I can fix a font issue (and I don't know how to do it using applescript so I made an automator program)
                        activate
                        delay 1
                    end tell
                    tell application "Microsoft Word"
                        save as active document file name "Macintosh HD:Users:Deve:Desktop:Materials for Applescript:CL:" & empName & " Letter.pdf" file format format PDF
                    end tell
                    tell application "Mail"
                        delay 2
                        set theMessage to make new outgoing message with properties {visible:true, subject:"Message", content:myVal}

                        tell theMessage
                            make new to recipient at end of to recipients with properties {name:empName, address:"[email protected]"}
                        end tell
                        tell theMessage
                            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:CL:" & empName & " Letter.pdf" as alias} at after the last paragraph
                            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:Work Book.pdf" as alias} at after the last paragraph
                            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:Picture File.pdf" as alias} at after the last paragraph
                            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:Lyrics.pdf" as alias} at after the last paragraph
                            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:Comparison.pdf" as alias} at after the last paragraph
                            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:Earlier Version.pdf" as alias} at after the last paragraph

                        end tell
                    end tell
                end tell
              end tell
          end tell
      end tell
  end tell
end tell

Как бы я смог зациклить весь этот процесс так, чтобы ячейки каждый раз перемещались вниз, чтобы empName и myVal брали свои значения из A5 и P5 ... затем A6 и P6 вплоть до 42?


person Dan    schedule 19.10.2014    source источник
comment
Поздравляю с первым постом. Измените заголовок, чтобы выразить свой конкретный вопрос - повторение сценария, перебирающего диапазон переменных. Это может помочь. Не используйте заглавные буквы в качестве акцента. Это заставляет многих людей просто пропустить ваш вопрос. Хорошо, что вы опубликовали рабочий код. Вы все еще можете немного изменить его, потому что горизонтальная полоса прокрутки препятствует глубокому анализу. Покажите, как вы пытались добиться своей цели и что тогда было не так. Это помогает получить полезные ответы. Добро пожаловать в StackOverflow Deve.   -  person Krzysztof Jabłoński    schedule 19.10.2014


Ответы (1)


Вам просто нужно сделать обозначение строки переменной и поместить свой код в цикл повторения, а затем увеличивать его на 1 после каждой итерации. Вот пример, как это сделать. (Я также мог бы воздержаться от удаления некоторых из ваших ошибочно вложенных блоков сообщений (не вставляйте блоки сообщений внутри блоков сообщений других приложений, если у вас нет для этого причин.

property firstRow : 5
property lastRow : 42

set r to firstRow
repeat until r is (lastRow + 1)

    tell application "Microsoft Excel"
        activate
        set empName to string value of range ("A" & r) of active sheet
        set myVal to string value of range ("P" & r) of active sheet
    end tell

    tell application "Finder"
        set theFile to "Macintosh HD:users:deve:desktop:C.dotx"
        open file theFile
        set the clipboard to myVal
    end tell

    tell application "Microsoft Word"
        activate
        tell application "System Events"
            tell application process "Microsoft Word"
                keystroke "v" using command down
                keystroke "a" using command down
            end tell
        end tell
    end tell

    tell application "font" -- this is just so I can fix a font issue (and I don't know how to do it using applescript so I made an automator program)
        activate
        delay 1
    end tell
    tell application "Microsoft Word"
        save as active document file name "Macintosh HD:Users:Deve:Desktop:Materials for Applescript:CL:" & empName & " Letter.pdf" file format format PDF
    end tell

    tell application "Mail"
        delay 2
        set theMessage to make new outgoing message with properties {visible:true, subject:"Message", content:myVal}

        tell theMessage
            make new to recipient at end of to recipients with properties {name:empName, address:"[email protected]"}
        end tell
        tell theMessage
            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:CL:" & empName & " Letter.pdf" as alias} at after the last paragraph
            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:Work Book.pdf" as alias} at after the last paragraph
            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:Picture File.pdf" as alias} at after the last paragraph
            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:Lyrics.pdf" as alias} at after the last paragraph
            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:Comparison.pdf" as alias} at after the last paragraph
            make new attachment with properties {file name:"Macintosh HD:Users:Deve:Desktop:Materials for Applescript:Earlier Version.pdf" as alias} at after the last paragraph
        end tell
    end tell

    set r to r + 1
end repeat

Я не проверял это на своей машине, но это отвечает на ваш основной вопрос. Опубликуйте любую последующую помощь, которая вам нужна.

person jweaks    schedule 20.10.2014
comment
Спасибо. Теперь он работает отлично. Есть ли способ получить его, чтобы он автоматически определял, какой номер lastRow основан на том, что было заполнено на листе Excel? Спасибо за вашу помощь. - person Dan; 20.10.2014
comment
Конечно. Если, например, ячейка в этой строке будет пустой, то после получения значения ячейки вы можете добавить: если myVal is then exit repeat - person jweaks; 20.10.2014