2021/01/10

Gg / 透過Google sheets(試算表)寄信

透過Google sheets(試算表)寄信

是將試算表當作資料來源

結合執行 Google Apps Script的功能

經過測試,一般的帳號似乎是無法使用

但是用G-Suite的帳號就可以使用

→後來發現是我個人帳號的問題,改用其他一般帳號就正常

按照範例就可以執行

可以依照自己的需求來修改

我修改了以下程式碼:

第7行–選取的列數

第9行–儲存格的範圍,對應試算表是A2到C2

需要留意的是 numRow是指從startRow開始取幾列

getRange(row, column, numRows, numColumns)的用法

numRows → The number of rows to return.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/**
* Sends emails with data from the current spreadsheet.
*/
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var numRows = 2; // Number of rows to process
// Fetch the range of cells A2:B3
var dataRange = sheet.getRange(startRow, 1, numRows, 3);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i in data) {
  var row = data[i];
  var emailAddress = row[0]; // First column
  var message = row[1]; // Second column
  var subject = row[2];//mail subject
  MailApp.sendEmail(emailAddress, subject, message);
  }
}

 

測試結果是OK的,收得到信

 

整理一下使用到的程式碼

javascipt是物件導向程式設計語言,建立物件之前必須先定義物件的規格形式,稱為『類別 (class)』,也就是先定義好這個物件長什麼樣子以及要做哪些事情。定義類別的樣式,稱為 『屬性 (Properties)』,要做的事或提供的方法,稱為『方法 (Methods)』。

SpreadsheetApp.getActiveSheet()

SpreadsheetApp-classs

Access and create Google Sheets files.

getActiveSheet()-Methods

Gets the active sheet in a spreadsheet.

備註:相對於excel,sheet就是工作表、spreadsheet是工作簿

getRange(row, column, numRows, numColumns)

Sheet-Class 的Methods

Returns the range with the top left cell at the given coordinates with the given number of rows and columns.

getRange(row, column, numRows, numColumns)

rowIntegerThe starting row index of the range; row indexing starts with 1
columnIntegerThe starting column index of the range; column indexing starts with 1
numRowsIntegerThe number of rows to return
numColumnsIntegerThe number of columns to return

 

getValues()

Sheet-Class 的Methods

Returns the rectangular grid of values for this range.
Returns a two-dimensional array of values, indexed by row, then by column.

備註:什麼是二維陣列:

一維陣列使用陣列名稱與一個索引值來指定存取陣列元素,例如:a[0]=(“123”),在陣列a的第一個位置放入123

二維陣列使用陣列名稱與兩個索引值來指定存取陣列元素,例如:b[0][1]=(“456”),在陣列b的第一列第二欄/行的位置放入456

第一個[ ]是列(Row) ;第二個[ ]是欄或行(Column);[i][j] ,表示要存取 i 列 j 行的元素。

 

sendEmail(recipient, subject, body)

MailApp-class的Methods

recipientStringthe addresses of the recipients, separated by commas
subjectStringthe subject line
bodyStringthe body of the email

 

參考資料

Google Apps Script的說明

Tutorial: Sending emails from a Spreadsheet

Youtube-利用 Google 試算表寄信給一群人

VBA / 使用Word VBA批次轉換成PDF

Word在2010的版本之後,都可以用另存新檔的方式將檔案存成PDF格式

檔案少的時候,還無所謂

但是檔案多的時候,這就會是很煩人的反覆操作

而一般的PDF工具,雖然可以批次轉檔

不過我到目前都找不到可以將轉檔的PDF輸出在原word檔的資料夾

即使是Adobe 的 Acrobat pro也無法這樣處理

後來在之前曾經介紹過的「彰化一整天」的網站中

找到符合我的需求

批次轉檔+儲存在來源資料夾-的 word VBA

程式運作方式就是以迴圈的方式重複執行 word另存成PDF的功能

使用的方式也相當直覺

不過要注意的是選取檔案的時候

不會篩選非word格式的檔案

這會造成在另存新檔的時候產生錯誤,導致程式中斷