Excel ChatGPTを利用する方法

2023年3月12日

English version.

ExcelからChatGPTを利用する方法を紹介します。

この手順はVBA・マクロを利用するためアプリケーション(Desktop)専用です。

クラウド(Online)でも利用したい場合はPower Automateを利用します。

BGM. Music by mubert.com
目次

手順

事前にChatGPTのAPIキー(シークレットキー)を取得します。

そして下のコードを利用ブックのVBAプロジェクトに張り付けてください。

Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Sub ChatGPT()
  ' 設定ここから。
  ' APIキー(シークレットキー)を指定。
  Dim APIkey As String: APIkey = "sk-******"
  
  ' 何回、待つかを指定。この回数を超えるとタイムアウト。1回あたり10秒待つ
  Dim tryMaxCount As Integer: tryMaxCount = 5
  
  ' 問い合わせるメッセージのセルを指定
  Dim CellAsk As String: CellAsk = "Sheet1!A1"
  
  ' 結果を受け取るセルを指定
  Dim CellAnswer As String: CellAnswer = "Sheet1!A2"
  
  ' 設定ここまで。
  
  Dim httpReq As Object: Set httpReq = CreateObject("MSXML2.XMLHTTP")
  Dim httpReqBody As String: httpReqBody = ""
  
  With httpReq

        .Open "POST", "https://api.openai.com/v1/completions", False
        .setRequestHeader "Content-Type", "application/json"
        .setRequestHeader "Authorization", "Bearer " & APIkey

        httpReqBody = "{""model"":""text-davinci-003"", ""prompt"":""" & Range(CellAsk).Value & """, ""max_tokens"":2024, ""temperature"":0, ""top_p"":1}"
        
        .send httpReqBody
        
        Dim count As Integer: count = 0
        Do While .readyState <> 4
          If count < tryMaxCount Then
            Call Sleep(10000)
          Else
            Exit Do
          End If
          
          count = count + 1
        Loop
        
        If .readyState = 4 Then
          Dim textStartIndex As Integer: textStartIndex = InStr(httpReq.responseText, "\n\n") + 4
          Dim textEndIndex As Integer: textEndIndex = InStr(textStartIndex, httpReq.responseText, """")
  
          Range(CellAnswer).Value = Replace(Mid(httpReq.responseText, textStartIndex, textEndIndex - textStartIndex), "\n", Chr(10))
        Else
          Range(CellAnswer).Value = "取得できませんでした(タイムアウト)"
        End If
        
  End With
  

  Set httpReq = Nothing
  MsgBox ("End")
End Sub

6~15行目は書き換えてください。

6行目の赤字部分を取得したAPIキー(シークレットキー)に変更します。

Dim APIkey As String: APIkey = "取得したAPIキー"

9行目の数字を大きくすると長い時間待ちます。サーバの負荷が大きい時は、ここが大きくないと処理が途中で終わってしまう可能性があります。

Dim tryMaxCount As Integer: tryMaxCount = 5

12行目にはChatGPTへの問い合わせ内容を設定するセルを指定します。

Dim CellAsk As String: CellAsk = "Sheet1!A1"

15行目にはChatGPTからの回答を設定するセルを指定します。

Dim CellAnswer As String: CellAnswer = "Sheet1!A2"

設定後、ワークシートにボタンなどを設置して、ChatGPTを呼び出してください。