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
- Navigate to Settings → Custom APIs
- Click + New API Key
- Configure your API key settings
- Copy your API key
See API Guide - Getting Started for details.
2. Open Excel Online Automate
- Open a blank Excel workbook in Excel 365 Online (or existing workbook)
- Click Automate → New Script
- Delete any default code in the editor
3. Add the Chat Aid Script
Copy and paste the following script into the Office Script editor:
// ===========================
// 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 APIsREMOVE_OPENING_TEXT: Optional text to remove from the start of responses (e.g., company name). Set to""to disable.
5. Save the Script
- Click Save (or press
Ctrl+S/Cmd+S) - Name your script (e.g., "Ask Chat Aid")
- The script will appear in your Automate menu
Usage
Asking Questions
-
Enter questions in cells (one per cell):
| What is our refund policy? |
| How do I reset my password? |
| What are the shipping options? | -
Select the cells containing your questions
-
Click Automate → Ask Chat Aid from the ribbon
-
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
- Batch Processing: Select multiple cells to process many questions at once
- Leave Space: Ensure columns to the right are empty for answers and sources
- Clear Questions: Write clear, specific questions for better answers
- Monitor Progress: Script runs synchronously - the workbook will be unresponsive during processing
- 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:
- Ensure you saved the script with a name
- Refresh the Excel workbook (close and reopen)
- Check that you're using Excel 365 Online (not desktop app)
- Verify your Microsoft 365 subscription includes Office Scripts
Authorization Errors
Problem: Script fails with authorization errors
Solutions:
- Verify your API key is correct in
CHATAID_API_KEY - Check that your API key is active in Chat Aid Settings
- Ensure no extra spaces or quotes around the API key
- Generate a new API key if needed
Script Hangs or Freezes
Problem: Excel becomes unresponsive when running script
Solutions:
- This is normal - the script runs synchronously and blocks the UI
- Wait for the script to complete (can take several minutes for many questions)
- Process fewer questions at a time (5-10 recommended)
- Avoid running on very large selections
Timeout Errors
Problem: "Error: Polling completed without success"
Solutions:
- The question may be too complex or data sources are slow
- Try asking a simpler question first
- Check your data sources are active and trained
- Reduce the number of questions processed at once
- 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
- List all common questions in Column A
- Select all question cells
- Run Automate → Ask Chat Aid
- Wait for completion (may take several minutes)
- Export or share the workbook
Building a Knowledge Base
- Organize questions by category in different sheets
- Process each category separately
- Review and edit answers as needed
- Use as internal documentation
Customer Support Templates
- Create templates with common questions
- Generate fresh answers when data sources update
- Copy answers into support tickets or emails
Related Documentation
- API Guide - Getting Started: Create and configure API keys
- API Guide - Asking Questions: Complete API documentation
- Custom APIs Settings: Manage API keys and permissions
- Data Sources: Connect data sources for better answers
- Google Sheets Integration: Alternative spreadsheet integration