0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

為替レートをExcelに記入するマクロ

Last updated at Posted at 2019-09-25

こんな「通貨一覧」ワークシートを作り、ボタンを押すと
excel1.png

こんな感じでレートが入るようにする。
excel2.png

マクロのコードは下記のようなかたち。
Open Exchange Rates( https://openexchangerates.org/ )からAPIキーを取得し、「設定」ワークシートのA1にAPIキーが書かれているものとする。
レート取得のボタンを押すとCommandButton1_click()が呼び出される。


Public Sub CommandButton1_Click()

	Dim jpnRate As Single
	Dim url, response As String
	Dim setting, rate As Worksheet
	Dim xmlHttp As Object
	Dim x As Integer

	Set setting = Worksheets("設定")
	Set rate = Worksheets("通貨一覧")

	If Not setting.Range("A1").Value = "" Then


	    url = "https://openexchangerates.org/api/latest.json?app_id=" & setting.Range("A1").Value
	    Set xmlHttp = CreateObject("MSXML2.XMLHTTP")
	    With xmlHttp
	        .Open "GET", url, False
	        .SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
	        .Send
	    End With

	    Dim jsonObj As Object
	    Set jsonObj = JsonConverter.ParseJson(xmlHttp.ResponseText)
	    NumRows = rate.Range("B2", rate.Range("B2").End(xlDown)).Rows.Count
	    rate.Range("B2").Select

	    For x = 2 To NumRows
	        'セルに書かれている通貨からレートを算出して記入
	        rate.Cells(x, 3).Value = jsonObj("rates")("JPY") / jsonObj("rates")(rate.Cells(x, 2).Value)
	    Next

	Else
	    msg = MsgBox("APIキーが設定されていません。" & vbCrLf & "Webサイトに移動しますか?", vbYesNo, "レート取得エラー")
	    If msg = vbYes Then
	        CreateObject("Wscript.Shell").Run ("https://openexchangerates.org")
	    End If
	End If

End Sub

JsonConverter.ParseJsonを使っているので、他の人の記事( https://qiita.com/emesh/items/0834a5ad373d2ade6a93 とか )を参考に。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?