Skip to main content

Excel 365 Online

Ask questions directly within Excel 365 Online and get AI-powered answers inserted into your spreadsheet.

Overview

The Chat Aid Excel 365 Online integration allows you to:

  • Select cells containing questions
  • Automatically query your Chat Aid knowledge base
  • Receive answers inserted in adjacent cells
  • Get source citations as clickable hyperlinks

This is perfect for:

  • Batch processing multiple questions
  • Creating FAQ documents
  • Building knowledge base exports
  • Documenting Q&A workflows

Setup

1. Get Your API Key

  1. Navigate to SettingsCustom APIs
  2. Click + New API Key
  3. Configure your API key settings
  4. Copy your API key

See API Guide - Getting Started for details.

2. Open Excel Online Automate

  1. Open a blank Excel workbook in Excel 365 Online (or existing workbook)
  2. Click AutomateNew Script
  3. Delete any default code in the editor

3. Add the Chat Aid Script

Copy and paste the following script into the Office Script editor:

Excel 365 Online Chat Aid Script
// ===========================
// CONFIGURATION
// ===========================

// Replace with your Chat Aid API key from Settings → Custom APIs
const CHATAID_API_KEY = "YOUR_API_KEY_HERE";

// Optional: Text to remove from the beginning of responses
// Set to empty string ("") if you don't want to remove any text
const REMOVE_OPENING_TEXT = "";

// ===========================
// SCRIPT (Do not modify below)
// ===========================

// Interface for the initial API response
interface InitialApiResponse {
ok: boolean;
promptId: string;
pollEndpoint: string;
timeInterval: number;
votingEndpoint: string;
}

// Interface for the source data
interface Source {
name: string;
url: string;
}

// Interface for the poll response data
interface PollResponseData {
canPoll: boolean;
response: string;
sources?: {
raw?: Source[];
};
}

// Interface for the poll response
interface PollResponse {
ok: boolean;
data: PollResponseData;
}

// Interface for the API response data
interface ApiResponseData {
response: string;
sources?: {
raw?: Source[];
};
}

function main(workbook: ExcelScript.Workbook) {
// Get the active worksheet and selected range
const sheet = workbook.getActiveWorksheet();
const selectedRange = workbook.getSelectedRange();
const values = selectedRange.getValues();

// Process each cell in the selected range
for (let i = 0; i < values.length; i++) {
for (let j = 0; j < values[i].length; j++) {
const inputValue = values[i][j]; // Current cell value
if (inputValue) { // Check if the cell is not empty
// Calculate the actual row and column positions
const row = selectedRange.getRowIndex() + i;
const col = selectedRange.getColumnIndex() + j;

// Call API and process the result
try {
const response: ApiResponseData = callHttpPostApi(inputValue as string);

// Extract and format the response
let responseText: string = response.response;

// Remove opening text if configured
if (REMOVE_OPENING_TEXT && responseText && responseText.length > REMOVE_OPENING_TEXT.length) {
if (responseText.substring(0, REMOVE_OPENING_TEXT.length) == REMOVE_OPENING_TEXT) {
responseText = responseText.substring(REMOVE_OPENING_TEXT.length, REMOVE_OPENING_TEXT.length + 1).toUpperCase() +
responseText.substring(REMOVE_OPENING_TEXT.length + 1);
}
}

// Write the response to the cell next to the input
sheet.getCell(row, col + 1).setValue(responseText);

// Process sources if available
if (response.sources && response.sources.raw) {
const sources: Source[] = response.sources.raw;
for (let k = 0; k < sources.length; k++) {
const source: Source = sources[k];
// Add hyperlink for each source
const cell = sheet.getCell(row, col + k + 2);
cell.setValue(source.name);
// Set the hyperlink formula
const formula: string = `=HYPERLINK("${source.url}","${source.name}")`;
cell.setFormula(formula);
}
}
} catch (error) {
// Write the error message
sheet.getCell(row, col + 1).setValue("Error: " + (error as Error).message);
}
}
}
}
}

// Function to call the API
function callHttpPostApi(inputValue: string): ApiResponseData {
const url = "https://api.chataid.com/chat/completions/custom";

// Create the request options
const payload = {
prompt: inputValue
};

// Office Scripts use XMLHttpRequest for HTTP requests
const xhr = new XMLHttpRequest();
xhr.open("POST", url, false); // false makes the request synchronous
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", CHATAID_API_KEY);

try {
xhr.send(JSON.stringify(payload));
if (xhr.status === 200) {
const responseData = JSON.parse(xhr.responseText) as InitialApiResponse;
// Check if we need to poll for results
if (responseData.pollEndpoint) {
return pollForResult(responseData.pollEndpoint);
}
// This shouldn't normally happen with the current API flow
return {
response: "Awaiting response...",
sources: { raw: [] }
};
} else {
throw new Error(`API request failed with status ${xhr.status}`);
}
} catch (error) {
console.log("Error making API request: " + error);
return {
response: "Error occurred",
sources: { raw: [] }
};
}
}

// Function to poll for results
function pollForResult(pollEndpoint: string): ApiResponseData {
const maxAttempts = 120;
for (let attempts = 0; attempts < maxAttempts; attempts++) {
// Sleep for 2 seconds between attempts
const sleepEndTime = new Date().getTime() + 2000;
while (new Date().getTime() < sleepEndTime) {
// Busy waiting
}

// Make the polling request
const xhr = new XMLHttpRequest();
xhr.open("GET", pollEndpoint, false); // synchronous request
xhr.setRequestHeader("Authorization", CHATAID_API_KEY);

try {
xhr.send();
if (xhr.status === 200) {
const pollData = JSON.parse(xhr.responseText) as PollResponse;
console.log(pollData);
if (pollData.data && pollData.data.response) {
return {
response: pollData.data.response,
sources: pollData.data.sources
};
}
}
} catch (error) {
console.log("Polling attempt #" + (attempts + 1) + " failed: " + error);
}
}
return {
response: "Error: Polling completed without success.",
sources: { raw: [] }
};
}

4. Configure the Script

At the top of the script, update the configuration:

// Replace with your Chat Aid API key
const CHATAID_API_KEY = "sk_live_abc123...";

// Optional: Remove opening text from responses
const REMOVE_OPENING_TEXT = "At Your Company, ";

Configuration Options:

  • CHATAID_API_KEY: Your API key from Settings → Custom APIs
  • REMOVE_OPENING_TEXT: Optional text to remove from the start of responses (e.g., company name). Set to "" to disable.

5. Save the Script

  1. Click Save (or press Ctrl+S / Cmd+S)
  2. Name your script (e.g., "Ask Chat Aid")
  3. The script will appear in your Automate menu

Usage

Asking Questions

  1. Enter questions in cells (one per cell):

    | What is our refund policy? |
    | How do I reset my password? |
    | What are the shipping options? |
  2. Select the cells containing your questions

  3. Click AutomateAsk Chat Aid from the ribbon

  4. Wait for answers to appear in adjacent cells:

    | What is our refund policy? | Our refund policy allows... | [Source 1] | [Source 2] |
    | How do I reset my password? | To reset your password... | [Source 1] |

Output Format

For each question:

  • Column +1: Answer text
  • Column +2: First source (clickable hyperlink)
  • Column +3: Second source (clickable hyperlink)
  • Column +4: Additional sources...

Best Practices

  1. Batch Processing: Select multiple cells to process many questions at once
  2. Leave Space: Ensure columns to the right are empty for answers and sources
  3. Clear Questions: Write clear, specific questions for better answers
  4. Monitor Progress: Script runs synchronously - the workbook will be unresponsive during processing
  5. Error Handling: If an error occurs, the error message will appear in the answer column

Troubleshooting

Script Not Appearing in Automate Menu

Problem: Script doesn't show in Automate menu after saving

Solutions:

  1. Ensure you saved the script with a name
  2. Refresh the Excel workbook (close and reopen)
  3. Check that you're using Excel 365 Online (not desktop app)
  4. Verify your Microsoft 365 subscription includes Office Scripts

Authorization Errors

Problem: Script fails with authorization errors

Solutions:

  1. Verify your API key is correct in CHATAID_API_KEY
  2. Check that your API key is active in Chat Aid Settings
  3. Ensure no extra spaces or quotes around the API key
  4. Generate a new API key if needed

Script Hangs or Freezes

Problem: Excel becomes unresponsive when running script

Solutions:

  1. This is normal - the script runs synchronously and blocks the UI
  2. Wait for the script to complete (can take several minutes for many questions)
  3. Process fewer questions at a time (5-10 recommended)
  4. Avoid running on very large selections

Timeout Errors

Problem: "Error: Polling completed without success"

Solutions:

  1. The question may be too complex or data sources are slow
  2. Try asking a simpler question first
  3. Check your data sources are active and trained
  4. Reduce the number of questions processed at once
  5. Contact support if the issue persists

Limitations

When using this integration, keep in mind that each question can take between 5 to 60 seconds to process, depending on its complexity. The script executes synchronously, which means that Excel will be unresponsive while it runs. Additionally, Microsoft imposes quotas on Office Script execution time, so it's important to process only a few questions at a time to prevent long periods of unresponsiveness.

Example Use Cases

Creating an FAQ Document

  1. List all common questions in Column A
  2. Select all question cells
  3. Run AutomateAsk Chat Aid
  4. Wait for completion (may take several minutes)
  5. Export or share the workbook

Building a Knowledge Base

  1. Organize questions by category in different sheets
  2. Process each category separately
  3. Review and edit answers as needed
  4. Use as internal documentation

Customer Support Templates

  1. Create templates with common questions
  2. Generate fresh answers when data sources update
  3. Copy answers into support tickets or emails