使用 TypeScript 在 Excel 中撰寫自動化腳本(Office Scripts in Excel)

如果是使用公司或是學校的帳號,在 Excel 的工具列中就會出現「自動化」的選項,可以使用 TypeScript 來撰寫 Office 腳本(Office Scripts)

如果非公司或學校的帳號會出現以下錯誤訊息:

點選「新增指令碼」後會出現「程式碼編輯器」,在裡面就可以使用 TypeScript 來撰寫自動化腳本,來操作 Excel 資料表:

常用指令

取得使用中的儲存格和工作表。
    
    // 取得使用中的工作表
    let selectedCell = workbook.getActiveCell();
    
    // 取得使用中的儲存格
    let selectedSheet = workbook.getActiveWorksheet();
    

找到指定的工作表並填入資料:
    
    // 取得名稱為「工作表1」的工作表
    const workSheet = workbook.getWorksheet("工作表1");
    if (!workSheet) {
        console.log(`找不到工作表1`);
        return;
    }

    // A1 儲存格
    const cell = workSheet.getCell(0, 0);

    // 填入文字:test
    cell.setValue("test");
    
    console.log(`getAddress: ${cell.getAddress()}`); // getAddress: 工作表1!A1
    console.log(`getRowIndex: ${cell.getRowIndex()}`); // getRowIndex: 0
    console.log(`getColumnIndex: ${cell.getColumnIndex()}`); // getColumnIndex: 0
    console.log(`getValue: ${cell.getValue()}`); // getValue: test
    
    // 使用座標取得儲存格
    const cell2 = workSheet.getRange("C14");
    

文章撰寫中...請稍後...

參考資料:
Microsoft.Learn - Fundamentals for Office Scripts in Excel

留言

張貼留言

如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com