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

共享全局数据,并通过共享运行时在 Excel 加载项的任务窗格和自定义函数之间发送事件。

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

以下说明介绍了如何在自定义函数和任务窗格代码之间共享全局变量。 本教程假定你已完成 Excel 自定义函数教程,使用脚本类型 JavaScript使用共享运行时项目的 Excel 自定义函数。 使用在该教程中创建的加载项完成以下说明。

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

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

  2. 在第 1 行,将以下代码插入到最顶部。 这将初始化一个名为 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。 该 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> 元素前,添加以下脚本。 当用户想存储或获取全局数据时,此代码将处理按钮单击事件。

    <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
    

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

  • 使用以下命令启动项目。

    npm run start
    

Excel 启动后,可使用“任务窗格”按钮来存储或获取共享数据。 在自定义函数的单元格中输入 =CONTOSO.GETVALUE(),以检索相同的共享数据。 或使用 =CONTOSO.STOREVALUE("new value") 将共享数据更改为新值。

注意

可以使用共享运行时从自定义函数调用某些 Office API。 更多细节请参见从自定义函数调用Microsoft Excel APIs

另请参阅