AppleScript在Excel中计算和删除字符

时间:2017-05-03 19:49:29

标签: excel count applescript

我遇到的问题是我的AppleScript删除了长度超过13个字符的文件名。我在B列中有一个文件名列表,我只需要13个字符,只不过是。我正在寻找脚本删除超过13的任何行。到目前为止,这有点工作,但不是删除所有。

        tell application "Microsoft Excel"
        activate
        open (choose file with prompt "Select the Excel file you wish to use.")
    end tell


    tell application "Microsoft Excel"
        tell active sheet
            autofit column "A:H"
        end tell
    end tell

set cellNumber to 2

    tell application "Microsoft Excel"
        activate
        repeat
            set fileName to get value of cell ("B" & cellNumber) as string
            set fncount to count characters of fileName
            if fncount is greater than 13 then
                delete entire row of cell ("B" & cellNumber)
                set endCount to 0
            else
                set endCount to endCount + 1
                if endCount > 100 then
                    exit repeat
                end if
            end if
            set cellNumber to cellNumber + 1
        end repeat
    end tell
    set endCount to 0

1 个答案:

答案 0 :(得分:0)

这不会删除所有内容,因为当脚本删除行时, Excel 会将行向上移动。

  

示例:脚本删除第二行,现在第二行是   第三行,所以脚本跳过一行

为避免这种情况,循环必须从最后一行的索引处开始。

使用used range属性获取最后一行。

tell application "Microsoft Excel"
    activate
    open (choose file with prompt "Select the Excel file you wish to use.")
    tell active sheet
        set cellNumber to 2
        autofit column "A:H"
        set lastR to count rows of used range -- get the index of the last row which contains a value
        repeat with i from lastR to cellNumber by -1 --  iterates backwards from the index of the last row 
            set fileName to string value of cell ("B" & i)
            if (count fileName) > 13 then delete row i
        end repeat
    end tell
end tell