下記記事でOffice アドインから独自のユーザー関数を呼び出す方法を紹介しましたが、今日はOffice アドインからSUMやAVERAGEといった、組み込みのワークシート関数を呼び出す方法を紹介します。
マニフェストファイル(manifest.xml)
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="TaskPaneApp">
<Id>d6b2207f-0f9a-485e-8252-ea1034c18cd2</Id>
<Version>1.0</Version>
<ProviderName>@kinuasa</ProviderName>
<DefaultLocale>ja-jp</DefaultLocale>
<DisplayName DefaultValue="組み込み関数呼び出しサンプル" />
<Description DefaultValue="Call built-in Excel worksheet functions"/>
<Hosts>
<Host Name="Workbook" />
</Hosts>
<DefaultSettings>
<SourceLocation DefaultValue="https://localhost/apps/test0216/index.html" />
</DefaultSettings>
<Permissions>ReadWriteDocument</Permissions>
</OfficeApp>
アドイン本体(index.html)
下記コードの通り、functionsオブジェクト経由でワークシート関数を呼び出すことができ、ワークシート関数によって返されるFunctionResultオブジェクトの「value」プロパティによって、結果を取得することができます。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Sample</title>
<link rel="stylesheet" href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.components.min.css">
<style>
#content-main {
background: #ffffff;
position: fixed;
top: 80px;
left: 0;
right: 0;
bottom: 0;
overflow: auto;
}
</style>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"></script>
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
<script src="https://unpkg.com/core-js/client/core.min.js"></script>
<script src="https://unpkg.com/@microsoft/office-js-helpers@0.7.4/dist/office.helpers.min.js"></script>
<script src="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/js/fabric.min.js"></script>
<script>
Office.initialize = function(reason){
$(document).ready(function(){
$("#run").click(run);
});
};
function run(){
Excel.run(function(context){
var range = context.workbook.worksheets.getActiveWorksheet().getRange("A1:A4");
range.values = [[100], [200], [300], [400]]; //セルの値設定
var ave = context.workbook.functions.average(range); //AVERAGE関数呼び出し
ave.load("value");
return context.sync().then(function(){
OfficeHelpers.UI.notify("", "" + ave.value, "success");
});
}).catch(function(error){
OfficeHelpers.UI.notify(error);
});
}
</script>
</head>
<body>
<div id="content-main">
<button id="run" class="ms-Button">
<span class="ms-Button-label">Run Code</span>
</button>
</div>
</body>
</html>
Office アドインから呼び出すことができるワークシート関数は「Calling built-in Excel worksheet functions using the Excel JavaScript API」をご参照ください。

![[Officeアドイン]Excel Custom functionsの紹介](https://www.ka-net.org/blog/wp-content/uploads/eyecatch-OfficeAddins-120x120.png)


















この記事へのコメントはありません。