2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

日数分ループして、1ヶ月分の日付を上から順番に表示させたい

Last updated at Posted at 2019-11-26

動作環境

Google Apps Script
Chrome

まえがき

Googleのスプレッドシートで、勤怠管理表を作った際に、日付1ヶ月分を新しいシートにマクロで表示したい場合などに、このページのコードが役に立つと思います。

感想

VBAに馴染んでいる自分には、GasのDate型の扱いがピンとこないです。

コード

function setDaysInAManth() {
  var strDate = "201902"   // ←この年月の数値をシート名にすること
  var strYear = strDate.slice(0,4);
  var strMonth = strDate.slice(4,6);
  
  Logger.log(strYear);
  Logger.log(strDate);
  Logger.log(strMonth);
  if (strMonth.slice(0,1) == "0") {
     strMonth = strMonth.slice(1,2);
  }
  Logger.log(strMonth);
  
  Logger.log(new Date(strYear, strMonth, 0));
  
  var DaysInAMonth = getLastDate(strYear, strMonth)
  Logger.log(DaysInAMonth);
    
  var ssTo = SpreadsheetApp.openById(スプレッドシートのナンバー)
  var shTo = ssTo.getSheetByName(strDate)
  
  // 日数分ループして、セルに1ヶ月分の日付を上から順番に表示させる
  var top_row = 5 
  for(var i=1;i<=31;i++){
    if (DaysInAMonth < i){
      shTo.getRange(i + top_row, AbcToNumber("A")).setValue("");
      continue
    }
    var memoDate = strYear + "/" + strMonth + "/" + (i)
    Logger.log(memoDate);
    shTo.getRange(i + top_row, AbcToNumber("A")).setValue(memoDate);
  }
}

// アルファベットを数値に変更する関数
// aのときに1を返したい
function AbcToNumber(strColumn) {
  var iNum = 0;
  var temp = 0;
  
  strColumn = strColumn.toUpperCase();
  for (i = strColumn.length - 1; i >= 0; i--) {
    temp = strColumn.charCodeAt(i) - 65; // 現在の文字番号;
    if(i != strColumn.length - 1) {
      temp = (temp + 1) * Math.pow(26,(i + 1));
    }
    iNum = iNum + temp
  }
  return iNum + 1;
}

// 月末の日付を取得する
function getLastDate (year_, month_) {
  var strDate = new Date(year_, month_, 0);
  return strDate.getDate()
}

あとがき

とりあえずコピペすれば動作はします。
アルファベットを数値に変更する関数と、月末の日付を取得する関数は、役に立ちます。(Excel VBAでアルファベットを数値に変換しないコード多いですよね)

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?