Excel-based Chatbots Powered by OpenAI API: A Game Changer for Business Automation

Introduction

The integration of the OpenAI API with Microsoft Excel is revolutionizing the way businesses interact with their data. One of the most exciting developments is the creation of Excel-based chatbots, which have the potential to automate various functions such as:

  1. Customer Service: Automate customer support by creating a chatbot that can handle frequently asked questions, troubleshoot issues, and provide guidance on product usage.
  2. Sales: Develop a sales chatbot that can assist customers in finding the right product, offer personalized recommendations, and even process orders directly from Excel.
  3. HR and Recruitment: Design a chatbot to automate the screening process, answer candidate queries, and schedule interviews.
  4. Inventory Management: Build a chatbot to help users track inventory levels, place orders for restocking, and provide real-time updates on product availability.
  5. Knowledge Management: Create a chatbot that can quickly retrieve information from internal databases, streamlining the process of accessing company data.

In this blog post, we will provide a detailed, step-by-step walkthrough for creating a chatbot within Excel using the OpenAI API. This guide is designed for novice Excel users, with easy-to-follow instructions and ready-to-use code snippets.

Note – Please be aware that this solution involves interacting with OpenAI’s API. I encourage users to familiarize themselves with OpenAI’s data usage policy (https://platform.openai.com/docs/data-usage-policy) and take necessary precautions to ensure the privacy and security of their data.

Step 1: Setting up the OpenAI API

First, sign up for an API key on the OpenAI website (https://beta.openai.com/signup/) and follow the instructions to get started.

Step 2: Creating a Chatbot Interface in Excel

  1. Open a new Excel workbook.
  2. In cell A1, type “User Input”.
  3. In cell B1, type “Chatbot Response”.
  4. Format the cells as desired for better readability.

Step 3: Enable Excel Developer Tab

  1. Click on “File” > “Options” > “Customize Ribbon”.
  2. Check the box next to “Developer” in the right column and click “OK”.

Step 4: Add a Button to Trigger Chatbot

  1. Click the “Developer” tab.
  2. Click “Insert” and select “Button (Form Control)”.
  3. Draw the button below the “User Input” and “Chatbot Response” cells.
  4. Right-click the button, select “Edit Text,” and type “Submit”.

Step 5: Write VBA Code for OpenAI API Integration

  1. Right-click the “Submit” button and click “Assign Macro”.
  2. In the “Assign Macro” window, click “New”.
  3. Copy and paste the following code into the VBA editor:
Option Explicit

Private Sub Submit_Click()
    Dim userInput As String
    Dim chatbotResponse As String
    
    ' Get user input from cell A2
    userInput = Range("A2").Value
    
    ' Call OpenAI API to get chatbot response
    chatbotResponse = GetOpenAIResponse(userInput)
    
    ' Display chatbot response in cell B2
    Range("B2").Value = chatbotResponse
End Sub

Function GetOpenAIResponse(userInput As String) As String
    Dim objHTTP As Object
    Dim apiKey As String
    Dim apiUrl As String
    Dim jsonBody As String
    Dim jsonResponse As String
    Dim json As Object
    
    ' Set your OpenAI API key here
    apiKey = "your_openai_api_key"
    
    ' Set OpenAI API endpoint URL
    apiUrl = "https://api.openai.com/v1/chat/completions"
    
    ' Create JSON request body
    jsonBody = "{""messages"": [{""role"": ""system"", ""content"": ""You are a helpful assistant.""}, {""role"": ""user"", ""content"": """ & userInput & """}], ""max_tokens"": 50, ""n"": 1, ""stop"": ""\n"", ""temperature"": 0.7}"
    
    ' Create an HTTP object
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    
    ' Send the request to OpenAI API
    With objHTTP
        .Open "POST", apiUrl, False
        .setRequestHeader "Content-Type", "application/json"
        .setRequestHeader "Authorization", "Bearer " & apiKey
        .send jsonBody
        jsonResponse = .responseText
    End With
    
    ' Create a JSON parser object
    Set json = CreateObject("MSXML2.DOMDocument.6.0")
    json.LoadXML jsonResponse
    
    ' Extract chatbot response from JSON and return it
    GetOpenAIResponse = json.SelectSingleNode("//content").Text
End Function

  1. Replace your_openai_api_key with your actual OpenAI API key.
  2. Save the VBA code by clicking the floppy disk icon or pressing Ctrl+S.
  3. Close the VBA editor by clicking the “X” in the top-right corner.

Step 6: Add Microsoft XML Reference for JSON Parsing

  1. Press Alt+F11 to open the VBA editor.
  2. Click “Tools” > “References” in the menu.
  3. Scroll down and check the box next to “Microsoft XML, v6.0” (or the latest version available).
  4. Click “OK” to close the “References” window.

Step 7: Test Your Excel Chatbot

  1. In cell A2, type a question or statement for your chatbot (e.g., “What is the capital of France?”).
  2. Click the “Submit” button.
  3. The chatbot’s response should appear in cell B2.

(Optional) Step 8: Add Context Awareness to Your Excel Chatbot

  1. In your Excel workbook, create a new sheet and rename it to “ConversationHistory”.
  2. In the VBA editor, modify the Submit_Click() subroutine by adding the following lines of code before the line chatbotResponse = GetOpenAIResponse(userInput):
    ' Save user input to ConversationHistory sheet
With Sheets("ConversationHistory")
.Cells(.Cells(.Rows.Count, 1).End(xlUp).Row + 1, 1).Value = "User: " & userInput
End With

3. Modify the GetOpenAIResponse() function by adding a new argument called conversationHistory:

Function GetOpenAIResponse(userInput As String, conversationHistory As String) As String

4. Update the Submit_Click() subroutine to pass the conversation history when calling the GetOpenAIResponse() function. Replace the line chatbotResponse = GetOpenAIResponse(userInput) with the following code:

    ' Get conversation history
Dim conversationHistory As String
conversationHistory = Join(Application.Transpose(Sheets("ConversationHistory").UsedRange.Value), " ")

' Call OpenAI API to get chatbot response
chatbotResponse = GetOpenAIResponse(userInput, conversationHistory)

5. Modify the JSON request body in the GetOpenAIResponse() function to include the conversation history. Replace the line jsonBody = "{""prompt"": ""Chatbot: " & userInput & "\", ""max_tokens"": 50, ""n"": 1, ""stop"": ""\n"", ""temperature"": 0.7}" with the following code:

    ' Create JSON request body with conversation history
jsonBody = "{""prompt"": """ & conversationHistory & " Chatbot: " & userInput & "\", ""max_tokens"": 50, ""n"": 1, ""stop"": ""\n"", ""temperature"": 0.7}"

6. Finally, update the Submit_Click() subroutine to save the chatbot’s response in the “ConversationHistory” sheet. Add the following lines of code after the line Range("B2").Value = chatbotResponse:

    ' Save chatbot response to ConversationHistory sheet
With Sheets("ConversationHistory")
.Cells(.Cells(.Rows.Count, 1).End(xlUp).Row + 1, 1).Value = "Chatbot: " & chatbotResponse
End With

With this optional modification in place, your Excel chatbot will now maintain a conversation history in the “ConversationHistory” sheet, which will be used to provide context-aware responses. The chatbot will be able to give more accurate and relevant answers based on the user’s previous interactions.

Conclusion

You now have a working Excel-based chatbot powered by the OpenAI API. This guide has provided you with a simple, step-by-step approach to creating a chatbot interface within Excel and integrating it with the OpenAI API using VBA code. While this example uses basic functionality, you can expand and adapt the code to create chatbots for various applications, such as customer service, sales, HR, inventory management, and knowledge management. With the power of the OpenAI API and the familiar Excel interface, businesses can create powerful, user-friendly tools to enhance operations and boost productivity.

This blogpost was created with help from ChatGPT Pro.

Using Power Update to refresh Excel Workbooks in Power BI Report Server

image

Happy Holidays!

With the latest release of Power BI Report Server, we introduced the ability to share and view Excel Workbooks in a web browser (assuming you Office Online Server setup for your server farm).  This included workbooks that had Power Pivot models embedded in them with external data connections that might need to be kept up to date.  However, there isn’t currently a way to automatically refresh the data for those workbooks on the server currently like you can in SharePoint.  Today, I’m excited to show you a way to get around that limitation using a tool called Power Update from a Power BI partner called PowerOn.

First announced on Rob Collie’s blog a couple years ago, Power Update is a standalone program that allows you to automatically refresh Excel files and load them to several destinations, including SharePoint, OneDrive, and Power BI Report Server.  Let me walk you through how simple it is to get started and use with PBIRS –

1. When you first start Power Update, you’ll want to create a new task.  Click “New” to get started –

Capture

2. Give your task a name and click Next –

screenshot2

3. You can decide how often you’d like to refresh your Excel workbook.  I chose to do it every hour on a daily basis

screenshot3

screenshot4

screenshot5

4. I can choose to either refresh a single file, or all the files in a particular folder.  I just need one workbook refreshed, so I choose that and proceed

screenshot6

5. For my publish location, I want to publish to Power BI, and then select the “Power BI Report Server” option.

Inkedscreenshot7_LI

6. I finish setting up the options for my server location and I’m done! (There are some optional items I can also choose in the last two screens, but I didn’t change anything on those for this exercise)

screenshot10

After I’ve set everything up, you’ll see the first task in my list is now populated.  As a test, I clicked the “Run Now” button to see if it works.  Everything was setup properly, so it’ll refresh the workbook, publish it to the server and then let me know it was successful.  I can even setup e-mail notifications to tell me this after each time it runs!

screenshot8

screenshot9

That’s it – it’s very simple to set up and manage your Excel Workbooks in Power BI Report Server and make sure they always have the latest data for your users.  And yes, anyone can use the public REST API’s for Power BI Report Server to do something like this on their own if they’d like.  Power Update just makes it easy to enable this functionality for their organization.

Power Update offers users both a free and paid version of their product – the free version offers all the functionality of the paid version, but is limited to only one workbook you can schedule and use.

Thanks for reading!

Updated demo VM for Power BI Report Server now available!

image

For those of you who enjoy using the test/dev/demo VM template the team has in Azure for Power BI Report Server, we’ve gone ahead and updated it with the latest preview we released a few weeks back.  With that update, we’ve made a few additional changes to the template as well –

– Office Online Server is now automatically installed and configured for you when you spin up a new environment.  There is also an Excel workbook available as one of the sample reports. (Please note – we do NOT currently setup an Analysis Services instance running in PowerPivot mode for you to use with the VM.  You can do that manually if you’d like by using the SQL install media already on the VM.)

– We now deploy two VM’s and setup a sample domain for them to allow you to use Office Online Server.  They will both be the same size you select in the VM setup process initially – you may re-size them if you’d like through the Azure portal at any time.  We did this to allow the widest number of regions access to the VM template, since not every VM size is available in every region.  This should help make sure you don’t accidentally select a VM that isn’t available in your region, and have the deployment fail for you. 

– We’ve added additional sample RDL reports with the VM for your use.

You can get started with the template in Azure here –http://bit.ly/2f2aWyn

I hope you find the latest updates valuable, and thanks for reading as always!

Learn more about Power BI Report Server at SQL Saturday Vancouver

Quick blog post today to let you all know I’ll be presenting at SQL Saturday Vancouver next Saturday, August 26th about Power BI Report Server.  This will be a chance to hear more about exactly what it is, how it can help you and your business AND discuss what new features and functionality will be coming soon.  And if you decide to attend, there’s probably a good chance you’ll see demos of the latest functionality we have planned for the next product update coming later this year!

If you’d like to attend SQL Saturday next week to see me or many other more talented presenters, you can learn more at the link here – http://www.sqlsaturday.com/635/EventHome.aspx

Look forward to seeing you there and being as confused by the funny looking money in Canada as I am.  See you next weekend!

Use Analyze in Excel + Excel Camera to create PowerPoint magic

image

So this blog post falls into the “I just think this is cool” bucket.  Did you know Excel had camera functionality?  Well, I didn’t.  And this despite the functionality being there since 2003(!).  This isn’t there by default, but if you turn it on in your Quick Access Toolbar, you can take advantage of it.  What’s so special about this functionality in particular?

Basically, it allows you to take a picture of a collection of cells in your workbook.  I know, amazing, right?  Stay with me here – it’s a picture, but it’s a LIVE picture.  Here’s a simple example using Excel 2016:

My table in my Excel workbook looks like this –
image

If I highlight those cells and use the camera tool, I can do the following in my workbook (I normally wouldn’t make the picture this big, but wanted to emphasize it was a picture and not just a linked table) –

image

Now I’ll change the numbers to text.  When I do that, the picture updates automatically as well –

image

And since it is a picture, I can do all the normal things I could do to a picture in terms of formatting –

image

So could I do something like this with a Pivot Table?  You bet, including one using “Analyze in Excel” in Power BI for the data!  I tried this myself against a sample report I loaded in PowerBI.com.  I chose “Analyze in Excel” from the ellipsis –

image

Then created my Pivot Table against the data and used the camera tool as I did in my earlier example.

image

Any change I made in the Pivot Table is reflected in the picture –

image

This is nice, but what I really want is this live picture in a PowerPoint deck that gets updated when my data is updated in Excel.  Let’s give that a try.

After I’ve selected the range in Excel with my camera tool, in PowerPoint I can choose “Paste Special” and select “Paste Link” so I can paste it as a “Microsoft Excel Worksheet Object”.  This will allow the data to updated dynamically whenever I have new data in my workbook. (You can also add Pivot Charts to your PowerPoint presentations via ‘Paste Link’, and the data will also update dynamically for those as well!)

image

For example, if I change the “AccountCount” to say “SSRS Rules!”, it changes dynamically.

image

I can also add a hyperlink to the picture back to the original report in Power BI if I wanted to jump there quickly during a presentation to do additional analysis on the data.

image

Something to keep in mind – if you share the PowerPoint deck with a user who doesn’t have access to the original Excel workbook, they can still open and use the presentation with the static images reflecting the last time the data was updated.  I think this is valuable, since I know often the workflow at some companies is basically “Hey so and so, I need that slide deck for the meeting tomorrow.  Can you update the slides from the previous meeting and send it to me?”

Thanks as always for reading  – maybe you already knew this trick, but if not, hopefully it’ll save you some time in the future!

Ten things you might have missed in the Technical Preview of Power BI Reports in SQL Server Reporting Services

image

Whew – this is my fourth (and final!) blogpost in four days around the Technical Preview for SQL Server Reporting Services.  It’s been a lot of work, but also a lot of fun putting these together.  For my final post, I wanted to touch on ten items you’ll see (and can try) in the preview to ensure you don’t miss them.

Before I do that, however, I wanted to take a moment to say “Thank you”.  This past week at PASS Summit 2016, and the reaction from the community to this entire preview, has been one of the highlights of my entire career.  I got to meet several of you for the first time at PASS, and as you learned very quickly, I’m not someone to sugarcoat things.  You all embraced this very unique preview and made the engineers who were on-site at PASS from the Reporting Services team feel like the rock stars they are.  That type of passion and energy is so infectious, again, I can’t thank you enough for letting the team know how excited you were with what we’ve delivered to date.  Our customers are the reason we fought so hard to bring this to you, and I promise, this is the just the first step.  We’re already back at it, working hard to bring you the first installable preview of this functionality as quickly as possible.

1. You can access your VM in Azure through a web browser

If you’d like other users to view and interact with the technical preview without remoting into the VM.  This is helpful if you’d like to show it to additional people in your organization, give users read-only access, etc.  Keep in mind, you’ll still need to do all creating/editing of Power BI Desktop reports on the VM directly using Remote Desktop.

To try this out, find the public IP address of the VM in Azure listed in the essentials section

image

Open a web browser on your local machine and type in the address/reports in the following format – http://8.8.8.8/reports (enabling https for the VM is something that is a little tricky to do, so I’ll have to decide whether that’s worth doing a future post around or not).  Enter your username and password for the VM, and you’ll be granted access to the report portal.
image

2. You can use embed the Power BI Reports just like mobile and paginated reports.

If you’d like to see your Power BI Report in an iFrame, you can add ?rs:Embed=true at the end of the report url.  For example, here is the embed url for the Sample Sales Report when connected directly to the VM via remote desktop – http://localhost/reports/powerbi/Sample%20Sales%20Report?rs:embed=true

image

3.  Mobile Reports and Power BI Reports both are available in the execution logs.

This is a common request for those folks interested in seeing when people ran certain reports and how often they did so.  If you go into the ReportServer database catalog via SQL Server Management Studio and run a query using the ExecutionLog3 SQL view, you’ll see log entries for both of these report types now show up –

image

4.  Direct url navigation is now available for KPI’s.

image

Users have so liked the new reporting services interface, they’d asked for an easy way to link to other content directly from the portal homepage so everyone can use the new portal as a starting point in their organization.  With this in mind, we added an additional option to KPI’s called “Direct Navigation”.  This allows you add a custom url as related content, just like you can in the portal currently, and simply bypass the current KPI pop-up action you get when you click on the KPI and go directly to the linked content.

For any KPI’s that you use this feature with, you’ll a little “link” in the upper right-hand corner of it so you can tell that it is enabled.  This will give the ability to create “dummy” KPI’s that you use just to link to outside content.

image

5.  You can turn report comments off for certain users by creating a custom role in SQL Server Management Studio and assigning it to them for folders/reports.

image

One piece of customer feedback we got when considering the comment feature was the need to give report owners the ability to restrict certain users from adding or viewing comments.  To accomplish that, we added new tasks for comments in Reporting Services that are assigned to security roles.  Security Roles in Reporting Services are managed through SQL Server Management Studio.  You can create a new role without these permissions and assign them to users accordingly by following the steps in this article.  (We’d recommend you hold off on changing the security roles for the Power BI reports in the Technical Preview, since we’re aware of an issue that was reported on another blog.)

6. You can favorite Power BI Reports just like any other report type

image

7. You can install another instance of Analysis Services on the same machine to have both Multidimensional and Tabular running simultaneously.

image

During setup, you get the option to run the VM with either Tabular or Multidimensional mode already running (along with demo Power BI content tailored for it).  However, if you really want to have both modes available on your machine, the developer edition installation files used for both the database engine and Analysis Services are located here on the VM – C:\SQLServer_13.0_Full

Simply add a new stand-alone instance of Analysis Services on the same machine and you’ll have both options available to build reports against.

8. You now have the option for a “List” view of your items in the portal

image

Simply toggle the layout option in the View menu in the portal to switch view types.

9.  A new, expanded context menu is available when you click the ‘…’ option for that item.

image

You’ll hear much more about items 8&9 in a future blog post on the Reporting Services team blog.

10. The Technical Preview VM will expire in six months.

Also note, the expiration date is six months from the date it was first made available in the portal.  Just be aware of this, and keep in mind you’ll probably want to migrate any content you put on there prior to this date.

And we’re done – finally, I can take a few hours to relax and watch the big Eagles/Cowboys game this evening.  I’m in such a good mood, I might not even care if the Eagles lose to Dallas.

Yeah, no, I’ll care – Go Birds!

Embed from Getty Images