教程:Microsoft Excel自定义函数和任务窗格之间共享数据和事件

使用共享运行时在 Excel 外接程序的自定义函数和任务窗格之间共享全局数据。 在本教程中,将添加用于读取和更新同一变量的函数和任务窗格控件。

先决条件

完成 Excel 自定义函数教程 ,并使用创建的加载项。 项目必须使用共享运行时项目类型和 JavaScript 脚本类型的 Excel 自定义函数。

共享自定义函数和任务窗格代码之间的状态

创建用于获取或存储共享状态的自定义函数

  1. 在 Visual Studio Code 中,打开 src/functions/functions.js。

  2. 在文件的开头,添加以下代码。 此代码初始化名为 的 sharedState全局变量。

    window.sharedState = "empty";
    
  3. 添加以下代码以创建将值存储到 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";
    }
    
  4. 添加以下代码以创建自定义函数,该函数获取 的 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;
    }
    
  5. 保存文件。

创建任务窗格控件以处理全局数据

  1. 打开 src/taskpane/taskpane.html。

  2. 在结束 </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>
    
  3. 在结束 </body> 元素之前,添加以下脚本来处理 Store 和 Get 按钮事件。

    <script>
      function storeSharedValue() {
        let sharedValue = document.getElementById('storeBox').value;
        window.sharedState = sharedValue;
      }
    
      function getSharedValue() {
        document.getElementById('getBox').value = window.sharedState;
      }
    </script>
    
  4. 保存文件。

  5. 生成项目。

npm run build

在自定义函数和任务窗格之间尝试共享数据

  1. 启动项目。
npm run start
  1. 在任务窗格中,输入一个值,然后选择“ 存储”。
  2. 在 Excel 单元格中,输入 以 =CONTOSO.GETVALUE() 检索相同的值。
  3. 在另一个单元格中,输入 =CONTOSO.STOREVALUE("new value") 以更新共享值。
  4. 在任务窗格中,选择“ 获取 ”以显示更新的值。

注意

共享运行时还允许自定义函数调用某些 Office API。 有关详细信息,请参阅 从自定义函数调用 Microsoft Excel API。

准备好停止开发服务器并卸载加载项时,运行以下命令。

npm run stop

另请参阅