Excel VBA を使用して curl コマンドを実行し、結果から「オーソリゼイション」の値だけを抽出し、後続の処理に渡すことは可能です。以下にその方法の概要を説明します。
方法の概要
Excel で入力欄を用意する
固定の入力欄(セル)に、curl コマンドに必要なパラメータ(URL、ヘッダー、データなど)を記載します。
VBA で Shell を使って curl を実行
VBA の Shell 関数を使って curl コマンドを外部で実行し、その結果をテキストファイルに出力します。
結果を解析
テキストファイルを VBA で読み取り、Authorization ヘッダーの値を抽出します。
後続処理
抽出した値を変数として他の処理に渡します。
実装例
- Excelのセルに入力
セル A1: URL(例:https://api.example.com/endpoint
)
セル A2: ヘッダー情報(例: Authorization: Bearer )
セル A3: POSTデータ(例: {"key": "value"})
Sub ExecuteCurlAndExtractAuthorization()
Dim curlCommand As String
Dim url As String
Dim headers As String
Dim postData As String
Dim outputFile As String
Dim resultFile As String
Dim authValue As String
Dim fileContent As String
Dim shellOutput As Double
' Excel から値を取得
url = ThisWorkbook.Sheets(1).Range("A1").Value
headers = ThisWorkbook.Sheets(1).Range("A2").Value
postData = ThisWorkbook.Sheets(1).Range("A3").Value
' 出力ファイル
resultFile = Environ("TEMP") & "\curl_result.txt"
' curl コマンドの作成
curlCommand = "curl -X POST """ & url & """ -H """ & headers & """ -d """ & postData & """ -o """ & resultFile & """"
' curl 実行
shellOutput = Shell("cmd.exe /c " & curlCommand, vbHide)
DoEvents ' 実行完了を待つ
' テキストファイルを開き、Authorization ヘッダーを抽出
On Error GoTo ErrorHandler
fileContent = ""
Open resultFile For Input As #1
Do While Not EOF(1)
Line Input #1, fileContent
If InStr(fileContent, "Authorization") > 0 Then
authValue = Trim(Split(fileContent, ":")(1)) ' "Authorization: ..." から値を抽出
Exit Do
End If
Loop
Close #1
' 後続処理に authValue を渡す
MsgBox "Authorization Value: " & authValue
Exit Sub
ErrorHandler:
MsgBox "エラーが発生しました: " & Err.Description
If Not EOF(1) Then Close #1
End Sub
注意点
curl のインストール
curl コマンドが実行可能であることを確認してください。Windows の場合、コマンドプロンプトで curl が利用可能かを確認します。
権限の設定
API の実行に必要な権限やトークンを適切に設定してください。
デバッグ
結果が期待通りでない場合、resultFile の内容を確認し、出力結果の解析が正しいかチェックしてください。
エラー処理
ネットワークエラーやコマンド実行エラーに備えたエラー処理を追加することをおすすめします。