Search code examples
excelmacosapplescriptcell

AppleScript & Excel: change cell based on another cell's value


Basic script will check each cell in a column and if that cell contains a certain value, then change the cell to the left of it to a another value.

So, something like:

tell application "Microsoft Excel"
    set theRange to find column 3
    repeat with x from 1 to 50 -- check the first 50 cells of column 3
    if theRange x value = "valid" then -- if the cell value/text is "valid"
        set currentValue to theRange x -1 value  -- get the value of the  previous cell in the same row
        set the value of theRange x -1 to currentValue & " paid" -- and append the word "paid"
    end repeat
end tell

Obviously, the above code is garbage, but hopefully you can see what I want:

Check each cell in column 3 (with only 50 rows used) If it has a given value, change the previous cell in the same row by appending a word

I assume this is simple if you are only using Excel but I want to have a script I can run over multiple files without hard coding each sheet


Solution

  • This script should do the change. It's usually recommended to declare sheets and workbooks, to prevent scripts from running on the wrong workbook or sheet. Change the values between the quotes to match your files, or remove the references to "of theSheet" if you don't want to use it.

    tell application "Microsoft Excel"
    set theSheet to sheet "sheet name" of workbook "workbook name"
    repeat with x from 1 to 50
        if value of range ("C" & x) of theSheet = "valid" then 
            set currentValue to (value of range ("B" & x) of theSheet as string) & " paid" 
            set the value of range ("B" & x) of theSheet to currentValue
        end if
    end repeat
    end tell