在Applescript中创建给定起始单元格和行/列偏移量的Excel范围

时间:2015-09-01 14:19:40

标签: applescript

我正在尝试使用Applescript将值插入Excel工作表中的单元格中。这些值作为列表列表保存在Applescript变量中(请参阅示例代码)。我已经知道如果我将这个变量插入到正确大小(行和列)的范围内,它会正确地将所有内容都放在正确的位置。

不幸的是,我插入的数据量可能会有所不同,因此我需要根据列表中的项目数来计算范围大小,而不是硬编码。我正在使用列表大小计算出起始单元格的偏移量,然后尝试创建一个从起始单元格到计算单元格偏移量的范围。

减少到最低限度,代码如下:

set myList to {{"Red", "Grapefruit", "1", ""}, {"Julie", "Heron", "2", "*"}}

tell application "Microsoft Excel"
    set myStartCell to range ("B18") of sheet 1 of active workbook
    set myEndCell to get offset myStartCell row offset ((count myList) -1) column offset ((count item 1 of myList) -1)
    set myRange to range {myStartCell, myEndCell} of sheet 1 of active workbook
    set value of myRange to myList
end tell

使用上面的代码,我收到错误消息“您尝试访问的对象不存在”,与该行有关

    set myRange to range {myStartCell, myEndCell} of sheet 1 of active workbook

在VBA中,类似的代码如下:

With ThisWorkbook.Worksheets(1)

Dim myStartCell As Range
Dim myEndCell As Range
Dim myRange As Range

Set myStartCell = Range("B18").Cells

Set myEndCell = myStartCell.Offset(rowOffset:=1, columnOffset:=3).Cells

Set myRange = .Range(myStartCell, myEndCell)

End With

如何使用Applescript实现与VBA行相同的功能

    Set myRange = .Range(myStartCell, myEndCell)

?或者,在给定起始单元格和行数和列数的情况下,是否有更好的方法来创建范围?

2 个答案:

答案 0 :(得分:1)

从行号和列号创建Excel中的范围很痛苦。这使用处理程序将数字转换为字母

set myList to {{"Red", "Grapefruit", "1", ""}, {"Julie", "Heron", "2", "*"}}

set numberOfColumns to (count item 1 of myList) - 1
set numberOfRows to (count myList) - 1
tell application "Microsoft Excel"
    set myStartCell to range "B18" of active sheet
    set myEndCell to get offset myStartCell row offset numberOfRows column offset numberOfColumns
    set columnLetter to my excelColumnToLetters(first column index of myEndCell)
    set myRange to range ("B18:" & columnLetter & first row index of myEndCell)
    set value of myRange to myList
end tell

-- converts the column number to the letter equivalent
to excelColumnToLetters(column)
    set letters to {}
    repeat while column > 0
        set remainder to column mod 26
        if remainder = 0 then set remainder to 26
        set beginning of letters to (remainder + 64)
        set column to (column - remainder) div 26
    end repeat
    return string id letters
end excelColumnToLetters

答案 1 :(得分:1)

您可以使用get address命令。

set myRange to range ("B18:" & (get address myEndCell)) of sheet 1 of active workbook
set value of myRange to myList

或者

set myRange to range ((get address myStartCell) & ":" & (get address myEndCell)) of sheet 1 of active workbook
set value of myRange to myList