如何将宏数据拉到Excel/Google 页面中 banner image

Implementation

How-To Guides

如何将宏数据拉到Excel/Google 页面中

通过Power Query或VBA将现实宏观经济数据从FXMacroData中拉入Excel,并通过Apps Script自动刷新和清洁行格式化将其拉入Google表格.

其他语言版本 English

电子表格仍然是宏观分析的最常见工具.无论您喜欢Excel还是Google表格,直接将现场央行和经济指标数据拉到单元格中,而不是手动复制值,将静态表变成自动更新的决策辅助.本指南将向您展示如何将FXMacroData连接到两个平台:Excel的Power Query和VBA,以及Google表的Apps Script.到最后,您关心的每个宏观数字都会自动刷新,而不必离开您的电子表单.

你将要建造什么

  • 执行查询 一个查询,只需单击即将任何指标转移到结构化表格中
  • 优化VBA 一个宏,直接将值写入命名的单元格,准备使用公式和图表
  • 谷歌应用程序脚本 一个脚本,将行写入页面标签,并更新时间驱动触发

预先要求

  • 汇率数据API键 登记在 订阅单一级关键涵盖许多指标终点
  • 没有. (用于电源查询) 优化 365/在线 Power Query 在 Windows/Mac 上内置,可在线使用
  • 谷歌帐户 任何访问 Google 页面和应用程序脚本的帐户 (不需要额外的软件)
  • 基本熟悉Excel公式 谷歌表格 没有编程背景需要用于Power查询部分

第一部分 Excel

第1部分 Excel

优秀提供两个路径,用于活跃API数据: 动力查询 没有代码,对分析师来说很好. 美国航空公司 (代码驱动,最适合当你需要将值写入特定单元格或从按或事件中触发逻辑时).

现在我们要做什么?

步骤1 了解API终点形状

每个FXMacroData指标都遵循相同的REST模式. 对于美国政策利率的请求看起来像这样:

GET https://fxmacrodata.com/api/v1/announcements/usd/policy_rate?api_key=YOUR_API_KEY&start=2020-01-01

JSON响应是一个带有 data 阵列:

{
  "data": [
    { "date": "2025-03-19", "val": 4.25, "announcement_datetime": "2025-03-19T18:00:00Z" },
    { "date": "2025-01-29", "val": 4.25, "announcement_datetime": "2025-01-29T19:00:00Z" },
    { "date": "2024-12-18", "val": 4.25, "announcement_datetime": "2024-12-18T19:00:00Z" }
  ]
}

每个记录都带有一个 date (年年-四月-七月),一个数字 val, 并且 提供时 第二级 UTC announcement_datetime由于每个指标终端点都有相同的形状,因此一个Power Query函数或一个VBA助手可以服务于所有这些. 应用程序文件现在我们要做什么?


现在我们要做什么?

步骤2 Excel 动力查询:通过 Web 连接器导入

电源查询系统是内置的 来自网络 接口可以使用任何JSON REST终端,

  1. 在Excel中,点击 数据 → 获取数据 → 从其他来源 → 从网络现在我们要做什么?
  2. 粘贴您的URL到对话框替换 YOUR_API_KEY 您的真正钥匙:
    https://fxmacrodata.com/api/v1/announcements/usd/policy_rate?api_key=YOUR_API_KEY&start=2020-01-01
  3. 按下 没有问题.启动了 Power Query Navigator,显示了 JSON 结构.
  4. 按下 数据 记录在导航器中扩展它,然后点击 转换为表 没有人知道. 没有问题.现在我们要做什么?
  5. 使用 扩展列 按 (双箭头图标) 在 Column1 标题将嵌套记录分解成平面列: date没有人知道. val没有人知道. announcement_datetime现在我们要做什么?
  6. 按下 关闭和加载 写出表格到一个新的表格.

提示:自动更新

右键单击加载表 → 表 → 外部数据属性 让我们 在打开文件时更新数据 设置一个 每N分钟更新一次 您的宏表将每次打开工作簿时保持当前状态.


现在我们要做什么?

步骤3 Excel 动力查询:使用可重复使用函数进行参数化

一旦单个指示符查询工作,将其推广到可重复使用的M函数,以便您可以在不重复 Web 连接器步骤的情况下拉出任何货币/指示符组合.

  1. 在查询编辑器中,右键点击左面板中的查询 → 创建函数现在我们要做什么?
  2. 给我一个名字. FetchMacroData现在我们要做什么?
  3. 取代其车身的M码:
// FetchMacroData — reusable Power Query function
// Parameters: currency (e.g. "usd"), indicator (e.g. "policy_rate"), apiKey, startDate
(currency as text, indicator as text, apiKey as text, startDate as text) =>
let
    url     = "https://fxmacrodata.com/api/v1/announcements/"
              & currency & "/" & indicator
              & "?api_key=" & apiKey
              & "&start=" & startDate,
    raw     = Json.Document(Web.Contents(url)),
    records = raw[data],
    tbl     = Table.FromList(records, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
    expand  = Table.ExpandRecordColumn(tbl, "Column1",
                {"date", "val", "announcement_datetime"},
                {"Date", "Value", "AnnouncementDatetime"}),
    typed   = Table.TransformColumnTypes(expand, {
                {"Date",  type date},
                {"Value", type number}
              })
in
    typed
  1. 关闭函数编辑器.现在创建一个新的 空白查询 对于每一个指标,你需要:
= FetchMacroData("usd", "inflation", "YOUR_API_KEY", "2022-01-01")
= FetchMacroData("eur", "policy_rate", "YOUR_API_KEY", "2022-01-01")

每个查询都加载到自己的表格中.该函数处理HTTP调用,JSON解析,列重命名和类型转换. 要添加一个新指标,添加一条空白查询不需要连接器向导. 在查找指标上找到指标 应用程序文件 对于任何货币对.


现在我们要做什么?

步骤4 Excel VBA:直接将值写入单元格

当您需要将值放置在特定命名的单元格中,将它们链接到现有公式中,或从按或工作簿开放事件中触发刷新时,VBA更适合.

打开 VBA 编辑器 (其他), 插入一个新模块 (插入 → 模块),并粘贴下面的:

Option Explicit

' ─────────────────────────────────────────────────────────────────
' FetchLatestIndicator
' Returns the most recent val for a given currency/indicator.
' Requires a reference to "Microsoft XML, v6.0" (VBA Editor →
' Tools → References → tick "Microsoft XML, v6.0").
' ─────────────────────────────────────────────────────────────────
Function FetchLatestIndicator(currency As String, indicator As String, _
                               apiKey As String) As Variant
    Dim http     As New MSXML2.XMLHTTP60
    Dim url      As String
    Dim json     As String
    Dim dataArr  As Variant
    Dim parsed   As Object

    url = "https://fxmacrodata.com/api/v1/announcements/" & _
          LCase(currency) & "/" & LCase(indicator) & _
          "?api_key=" & apiKey & "&limit=1"

    http.Open "GET", url, False
    http.setRequestHeader "Accept", "application/json"
    http.Send

    If http.Status <> 200 Then
        FetchLatestIndicator = CVErr(xlErrValue)
        Exit Function
    End If

    ' ── Minimal JSON parser (no external library needed) ──────────
    ' Locate the first "val": number pattern after "data":[{
    Dim pos     As Long
    Dim valStr  As String
    json = http.responseText
    pos  = InStr(json, """val"":")
    If pos = 0 Then
        FetchLatestIndicator = CVErr(xlErrNA)
        Exit Function
    End If
    pos    = pos + Len("""val"":")
    valStr = Mid(json, pos, 20)
    ' Trim to the actual number (stop at comma, space, or brace)
    valStr = Split(Trim(valStr), ",")(0)
    valStr = Split(valStr, "}")(0)
    valStr = Trim(valStr)
    FetchLatestIndicator = CDbl(valStr)
End Function


' ─────────────────────────────────────────────────────────────────
' RefreshMacroDashboard
' Writes the latest value of several indicators into named cells.
' Define Named Ranges (Formulas → Name Manager) matching the keys
' used in the pairs array below.
' ─────────────────────────────────────────────────────────────────
Sub RefreshMacroDashboard()
    Dim apiKey As String
    apiKey = "YOUR_API_KEY"   ' ← replace with your key

    Dim pairs(5, 1) As String
    pairs(0, 0) = "usd" : pairs(0, 1) = "policy_rate"
    pairs(1, 0) = "eur" : pairs(1, 1) = "policy_rate"
    pairs(2, 0) = "gbp" : pairs(2, 1) = "policy_rate"
    pairs(3, 0) = "usd" : pairs(3, 1) = "inflation"
    pairs(4, 0) = "usd" : pairs(4, 1) = "unemployment"
    pairs(5, 0) = "usd" : pairs(5, 1) = "gdp"

    Dim i   As Integer
    Dim val As Variant
    Dim nm  As String
    For i = 0 To 5
        val = FetchLatestIndicator(pairs(i, 0), pairs(i, 1), apiKey)
        nm  = UCase(pairs(i, 0)) & "_" & pairs(i, 1)
        On Error Resume Next
        ThisWorkbook.Names(nm).RefersToRange.Value = val
        On Error GoTo 0
    Next i

    MsgBox "Dashboard updated — " & Now(), vbInformation, "FXMacroData"
End Sub

如何将它连接到按上

在工作表中,请进入 插入 → 形状画一个圆形矩形,右键按它 → 赋值宏 选择 RefreshMacroDashboard. 一键刷新了您的仪表板中的每个指示器.您也可以自动运行它在文件开放通过调用它从 Workbook_Open()ThisWorkbook 代码模块


第二部分 谷歌表

第二部分 谷歌表

谷歌应用程序脚本是一个直接嵌入谷歌工作空间的JavaScript运行时. 它在谷歌基础设施上运行于服务器端,因此没有什么需要安装.您可以通过 UrlFetchApp 并且将结果写入电子表格中, SpreadsheetApp时间驱动的触发器可以让你安排自动更新.

五步 没有

步骤5 打开应用程序脚本编辑器

  1. 打开 页面.谷歌.com 创建一个新的空白电子表格.
  2. 按下 扩展 → 应用程序脚本现在我们要做什么?
  3. 项目更名为 货币数据加载器 (左上角的字段)
  4. 删除默认的 myFunction() 位置保持器.

保存您的API密钥

现在去 项目设置 → 脚本属性 → 添加属性添加一个名为 FXMACRODATA_API_KEY 然后将键粘贴为值. 下面的代码通过运行时读取它 PropertiesService.getScriptProperties() 您的密钥从来没有出现在脚本文件中.


现在我们要做什么?

步骤6 写下获取辅助器和页面编辑器

贴上下面的代码 Code.gs三个功能处理取,规范和写:

// ── Config ──────────────────────────────────────────────────────
const BASE_URL = 'https://fxmacrodata.com/api/v1';

// List of {currency, indicator} pairs to load.
// Add or remove rows to customise your dashboard.
const INDICATORS = [
  { currency: 'usd', indicator: 'policy_rate'  },
  { currency: 'usd', indicator: 'inflation'    },
  { currency: 'usd', indicator: 'unemployment' },
  { currency: 'eur', indicator: 'policy_rate'  },
  { currency: 'gbp', indicator: 'policy_rate'  },
  { currency: 'aud', indicator: 'policy_rate'  },
];


// ── Fetch helper with retry ─────────────────────────────────────
/**
 * Fetches the latest N records for a currency/indicator pair.
 * Retries up to maxRetries times with exponential back-off.
 *
 * @param {string} currency   - e.g. 'usd'
 * @param {string} indicator  - e.g. 'policy_rate'
 * @param {string} apiKey
 * @param {number} limit      - number of records to return (default 12)
 * @param {number} maxRetries
 * @returns {Array} array of {date, val, announcement_datetime} objects
 */
function fetchIndicator(currency, indicator, apiKey, limit = 12, maxRetries = 3) {
  const url = `${BASE_URL}/announcements/${currency}/${indicator}`
            + `?api_key=${apiKey}&limit=${limit}`;

  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      const resp = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
      if (resp.getResponseCode() === 200) {
        return JSON.parse(resp.getContentText()).data || [];
      }
    } catch (e) {
      if (attempt < maxRetries - 1) {
        Utilities.sleep(Math.pow(2, attempt) * 1000); // 1 s, 2 s, 4 s
      }
    }
  }
  return [];
}


// ── Sheet writer ────────────────────────────────────────────────
/**
 * Writes all indicator rows to a sheet named 'MacroData'.
 * Creates the sheet if it does not exist; clears it on each run
 * so stale rows are removed.
 */
function refreshMacroData() {
  const apiKey = PropertiesService.getScriptProperties()
                                  .getProperty('FXMACRODATA_API_KEY');
  if (!apiKey) {
    throw new Error('FXMACRODATA_API_KEY script property is not set.');
  }

  const ss        = SpreadsheetApp.getActiveSpreadsheet();
  let   sheet     = ss.getSheetByName('MacroData');
  if (!sheet) {
    sheet = ss.insertSheet('MacroData');
  }
  sheet.clearContents();

  // Header row
  const headers = ['Currency', 'Indicator', 'Date', 'Value', 'AnnouncementDatetime'];
  sheet.appendRow(headers);

  // Style header
  const headerRange = sheet.getRange(1, 1, 1, headers.length);
  headerRange.setBackground('#1e3a5f');
  headerRange.setFontColor('#ffffff');
  headerRange.setFontWeight('bold');

  // Data rows
  INDICATORS.forEach(({ currency, indicator }) => {
    const records = fetchIndicator(currency, indicator, apiKey);
    records.forEach(r => {
      sheet.appendRow([
        currency.toUpperCase(),
        indicator,
        r.date,
        r.val,
        r.announcement_datetime || ''
      ]);
    });
  });

  // Auto-resize columns for readability
  sheet.autoResizeColumns(1, headers.length);
}

现在我们要做什么?

步骤7 运行并验证

  1. 按下 保存 在编辑器工具中的图标 (软盘).
  2. 选择 refreshMacroData 在运行按 (▶) 旁边的函数下拉窗口中.
  3. 按下 现在就跑吧.. 第一个运行请求访问电子表格并执行外部HTTP请求的权限点击 检查权限 → 允许现在我们要做什么?
  4. 转到电子表格.一个新的选项卡叫做 宏数据 现在应该包含这样的行:
货币 标志 时间 价值 发布时间
美元 政策_利率 现在我们要做什么? 其他 没有任何其他.
美元 货币膨胀 现在我们要做什么? 其他 没有任何其他.
美元 失业率 现在我们要做什么? 其他 现在我们要做什么?

现在我们要做什么?

步骤8 计划自动更新

时间驱动的触发器呼叫 refreshMacroData 没有任何手动操作.

  1. 在应用程序脚本编辑器中,点击 触发器 在左侧中,有图标 (钟).
  2. 按下 添加触发器 (右下角)
  3. 已经设置 选择要运行哪个函数 没有人知道. refreshMacroData现在我们要做什么?
  4. 已经设置 选择事件源 没有人知道. 时间驱动现在我们要做什么?
  5. 已经设置 选择基于时间的触发类型 没有人知道. 日计时器现在我们要做什么?
  6. 已经设置 选择一天的时间 举例来说 时间:上午7点上午8点 (欧洲公开赛前).
  7. 按下 保存触发器出现在触发列表中.

提示:每小时触发发布日监测

在有重大影响的发布日美国CPI,NFP或央行决定日切换触发器到 计时器 → 每小时 所以,当API更新后 (通常在官方发布后几秒钟内) 页面就会捕获新读数. 货币膨胀 现在我 农业以外的工资 终点运输第二级 announcement_datetime 值,以便您可以准确确定每一个读数何时发布.


现在我们要做什么?

步骤 9 将最新值拉入任何具有自定义函数的单元格

添加下面的函数到 Code.gs 如果您想直接引用宏值在单元格公式中,就像 GOOGLEFINANCE() 但对于央行数据:

/**
 * Custom Sheets function: returns the latest value for a currency/indicator.
 *
 * Usage in a cell:  =FXMD("usd","policy_rate")
 *
 * @param {string} currency   e.g. "usd"
 * @param {string} indicator  e.g. "policy_rate"
 * @customfunction
 */
function FXMD(currency, indicator) {
  const apiKey  = PropertiesService.getScriptProperties()
                                   .getProperty('FXMACRODATA_API_KEY');
  const records = fetchIndicator(currency, indicator, apiKey, 1);
  if (!records || records.length === 0) return null;
  return records[0].val;
}

在保存后,键入 =FXMD("usd","policy_rate") 在任何单元格中. 页面调用函数,从API中获取,并返回当前值. 将其与相邻单元中的货币标签结合起来,构建一个紧的概要面板.

支持的指标

任何从FXMacroData目录中获取的指标都能运行 policy_rate没有人知道. inflation没有人知道. unemployment没有人知道. gdp没有人知道. pmi没有人知道. retail_sales更多的. 应用程序文件 查看每个货币的完整列表,或者使用 汇率仪表板 视觉探索指标.


总结:

总结

您已经将FXMacroData连接到Excel和Google Sheets:

  • 执行查询 可参数化的M函数,将任何指标加载到结构化表格中,并在开放文件时更新.
  • 优化VBA 一个宏,将每个指标的最新值写入命名的单元格中,可分配到一个按上.
  • 谷歌应用程序脚本 一个 refreshMacroData() 函数可以建立一个完整的MacroData选项卡,加上一个 =FXMD() 根据每个单元格的定制公式, 两个都会在时间驱动的触发器上自动更新.

从这里开始,考虑在更多的指标中进行分层,例如,添加 基本通货膨胀 总体通胀,或拉 美国 对于多种货币来说,比较不同地区的增长势头. INDICATORS 它们的数组或M函数调用.

AI Answer-Ready

Key Facts

Page
How To Macro Data Excel Google Sheets
Section
Articles
Canonical URL
https://fxmacrodata.com/articles/how-to-macro-data-excel-google-sheets
Source
FXMacroData editorial and official publisher references
Last Updated
2026-04-22 12:36 UTC

Provenance And Trust

Cite the canonical URL and source field above. Where available, this page maps to official publisher releases and timestamped updates.

Quick Q&A

What is this page about? This page explains How To Macro Data Excel Google Sheets with directly usable context for trading, research, and API workflows.

What source should be cited? Use the canonical URL and the listed source field; cite official publisher references when available.

How fresh is this content? The last updated value above reflects the page metadata or latest available data timestamp.

Can this be used in AI assistants? Yes. This section is intentionally structured for retrieval and citation in chat assistants.

Prompt Packs

Use these in ChatGPT, Claude, Gemini, Mistral, Perplexity, or Grok for consistent source-aware outputs.

Blogroll