Home » excel » How to connect excel to microsoft's QnA Maker (VBA)

How to connect excel to microsoft's QnA Maker (VBA)

Posted by: admin May 14, 2020 Leave a comment

Questions:

I receive excel files with questions on a regular basis (I have the answers from previous iterations. the questions are always similar) and I would like to automate the replies. I have created a Knowledge Base in Microsofts QnAMaker with all the question/answer pairs.

How can I call Microsofts QnAMaker to answer my questions from excel. I have been looking for a vba examples but I havent found anything so far.
I believe I need to make a HTTP request with authorization from excel using vba and then process the response.
Would someone have an idea on how I can make a request and process it?

Any help appreciated. Thank you!

These are the sample details QnAMaker provides to make the call:

 POST /knowledgebases/d02d1d7e-1bc0-461a-8074-37749cae41b9/generateAnswer
 Host: https://rfp1.azurewebsites.net/qnamaker
 Authorization: EndpointKey cec4b630-9e77-474f-8df4-e6430a5678c8
 Content-Type: application/json
 {"question":"<Your question>"}
How to&Answers:

I found two ways to do this. First is with VBA. Second is with Power Queries.

VBA

Optional Setup

enter image description here

  1. Add the Developer tab to the ribbon by going to File > Options > Customize Ribbon > Check Developer

  2. Go to the Developer tab, then Insert > Button

  3. Name the macro “GetReplies”

  4. Click New

Notes:

  • My QnAKB is based off of this FAQ, mostly.

VBA Setup

  1. From the Developer tab, click the Visual Basic button (if it didn’t open automatically)

  2. Go to Tools > References and enable the following libraries:
    enter image description here

  3. Import this JSON library following the installation instructions

  4. Copy/paste this:

VBA code:

Sub GetReplies()

    'User Settings
    Dim questionWorksheetName As String, questionsColumn As String, firstQuestionRow As String, kbHost As String, kbId As String, endpointKey As String

        questionWorksheetName = "Sheet1"
        questionsColumn = "A"
        firstQuestionRow = "2"

        kbHost = "https://**********.azurewebsites.net/qnamaker"
        kbId = "*******-****-****-****-**********"
        endpointKey = "*********-****-****-****-***********"

    'Non-User Settings
    Dim questionWorksheet As Worksheet
        Set questionWorksheet = Sheets(questionWorksheetName)
    Dim startCell As String
        startCell = questionsColumn & firstQuestionRow
    Dim questionsRange As Range
        Set questionsRange = questionWorksheet.Range(startCell, questionWorksheet.Range(startCell).End(xlDown))

    'Loop through all non-blank cells
    Dim answer As String
    For Each cell In questionsRange
        If Not IsEmpty(cell) Then
            answer = GetAnswer(cell.Value, kbHost, kbId, endpointKey)
            'Add answer to cell
            cell.Offset(0, 1).Value = answer
        End If
    Next

End Sub

Function GetAnswer(question, kbHost, kbId, endpointKey) As String
    'HTTP Request Settings
    Dim qnaUrl As String
        qnaUrl = kbHost & "/knowledgebases/" & kbId & "/generateAnswer"
    Dim contentType As String
        contentType = "application/json"
    Dim data As String
        data = "{""question"":""" & question & """}"

    'Send Request
    Dim xmlhttp As New MSXML2.XMLHTTP60

    xmlhttp.Open "POST", qnaUrl, False
        xmlhttp.SetRequestHeader "Content-Type", contentType
        xmlhttp.SetRequestHeader "Authorization", "EndpointKey " & endpointKey
    xmlhttp.Send data

    'Convert response to JSON
    Dim json As Dictionary
    Set json = JsonConverter.ParseJson(xmlhttp.ResponseText)

    Dim answer As Dictionary

    For Each answer In json("answers")
    'Return response
        GetAnswer = answer("answer")
    Next

End Function
  1. Edit the “User Settings” at the top, appropriately

After running, I get:

enter image description here

Power Queries

Create HTTP Connection Query

  1. Data Tab > Get Data > From Other Sources > Blank Query

  2. Click Advanced Editor and copy paste

Code:

(Question as text) =>
let
    url = "https://***host****.azurewebsites.net/qnamaker/knowledgebases/****kbId******/generateAnswer",
    endpointKey = "****endpointKey*****",
    table = Excel.CurrentWorkbook(){[Name="Answers"]}[Content],
    row = Table.SelectRows(table, each ([Answer] = Question)),
    body = "{""question"":""" & Question & """}",
    Parsed_JSON = Json.Document(body),
    BuildQueryString = Uri.BuildQueryString(Parsed_JSON),
    headers = [#"Content-Type"="application/json", #"Authorization"="EndpointKey " & endpointKey],
    content = Text.ToBinary(body),
    Source = Json.Document(Web.Contents(url, [Headers = headers, Content = content])),
    answers = Source[answers],
    answers1 = answers{0},
    answer = answers1[answer]
in
    answer
  1. Replace variables as necessary

  2. Rename the Query to “GetAnswer”

  3. Exit from Power Query, saving changes

Create the Table

  1. Create a table with your questions

enter image description here

  1. Select the table. Table Design Tab > Rename the table to Answers

  2. With whole table selected, Data tab > From Table/Range

  3. Add Column > Invoke Custom Function

  4. Column name = Answers, Function query = GetAnswer, Question: ColumnName = Question

  5. Ok. Ok/Exit/Save

You can then add a question to the table, go to the sheet where the Question/Answer table was created and click Refresh to get new answers.