使用共享运行时在 Excel 外接程序的自定义函数和任务窗格之间共享全局数据。 在本教程中,将添加用于读取和更新同一变量的函数和任务窗格控件。
先决条件
完成 Excel 自定义函数教程 ,并使用创建的加载项。 项目必须使用共享运行时项目类型和 JavaScript 脚本类型的 Excel 自定义函数。
共享自定义函数和任务窗格代码之间的状态
创建用于获取或存储共享状态的自定义函数
在 Visual Studio Code 中,打开 src/functions/functions.js。
在文件的开头,添加以下代码。 此代码初始化名为 的
sharedState全局变量。window.sharedState = "empty";添加以下代码以创建将值存储到
sharedState的自定义函数。/** * Saves a string value to shared state with the task pane * @customfunction STOREVALUE * @param {string} value String to write to shared state with task pane. * @return {string} A success value */ function storeValue(sharedValue) { window.sharedState = sharedValue; return "value stored"; }添加以下代码以创建自定义函数,该函数获取 的
sharedState当前值。/** * Gets a string value from shared state with the task pane * @customfunction GETVALUE * @returns {string} String value of the shared state with task pane. */ function getValue() { return window.sharedState; }保存文件。
创建任务窗格控件以处理全局数据
打开 src/taskpane/taskpane.html。
在结束
</main>元素之后,添加以下 HTML 以创建用于存储和检索全局数据的控件。<ol> <li> Enter a value to send to the custom function and select <strong>Store</strong>. </li> <li> Enter <strong>=CONTOSO.GETVALUE()</strong> into a cell to retrieve it. </li> <li> To send data to the task pane, in a cell, enter <strong>=CONTOSO.STOREVALUE("new value")</strong> </li> <li>Select <strong>Get</strong> to display the value in the task pane.</li> </ol> <p>Store new value to shared state</p> <div> <input type="text" id="storeBox" /> <button onclick="storeSharedValue()">Store</button> </div> <p>Get shared state value</p> <div> <input type="text" id="getBox" /> <button onclick="getSharedValue()">Get</button> </div>在结束
</body>元素之前,添加以下脚本来处理 Store 和 Get 按钮事件。<script> function storeSharedValue() { let sharedValue = document.getElementById('storeBox').value; window.sharedState = sharedValue; } function getSharedValue() { document.getElementById('getBox').value = window.sharedState; } </script>保存文件。
生成项目。
npm run build
在自定义函数和任务窗格之间尝试共享数据
- 启动项目。
npm run start
- 在任务窗格中,输入一个值,然后选择“ 存储”。
- 在 Excel 单元格中,输入 以
=CONTOSO.GETVALUE()检索相同的值。 - 在另一个单元格中,输入
=CONTOSO.STOREVALUE("new value")以更新共享值。 - 在任务窗格中,选择“ 获取 ”以显示更新的值。
注意
共享运行时还允许自定义函数调用某些 Office API。 有关详细信息,请参阅 从自定义函数调用 Microsoft Excel API。
准备好停止开发服务器并卸载加载项时,运行以下命令。
npm run stop