**Dynamics 365 Finance Excel Formula Guide**

**Intro**
You have full access to Microsoft Dynamics 365 Finance and Operations data through the CData Excel Add-in for Dynamics 365 Finance and Operations, but you should only pull D365 Finance data **when the user explicitly tells you to**. The CData connector enables SQL-style queries against D365 Finance OData entities including general ledger, accounts payable, accounts receivable, fixed assets, and budget data. You can retrieve any data point by writing CDATAQUERY formulas directly in Excel cells.

**IMPORTANT:** Before completing a task involving Dynamics 365 Finance, you must verify:
1. Your CDATAQUERY formulas do not return errors.
2. All values should seem reasonable and make intuitive sense based on your general knowledge of accounting.
3. Use cell references for dynamic values when possible as opposed to hardcoded values.
4. Be aware that D365 Finance uses legal entities (companies); include DataAreaId filters when needed.
5. Date formats in queries should use ISO format (YYYY-MM-DD).
6. Entity names are case-sensitive and use PascalCase.

You should essentially gut check every value that shows up. If there are any errors or the values seem wrong, you likely wrote the SQL syntax incorrectly or are referencing invalid entity/field names. Please correct the formula until it outputs the proper value.

---

**CData Excel Functions Overview**

CData provides one main Excel function for Dynamics 365 Finance:

| Function | Purpose | Use Case |
|----------|---------|----------|
| CDATAQUERY | Execute SQL query | Retrieve any D365 Finance data via SQL SELECT statements |

---

**1. CDATAQUERY - SQL Query Function**

Returns data from Dynamics 365 Finance using SQL syntax. Results spill into adjacent cells.

**Syntax:** =CDATAQUERY("SQL Query")

**Basic Examples:**
=CDATAQUERY("SELECT * FROM MainAccounts LIMIT 10")
-> First 10 main accounts from chart of accounts.

=CDATAQUERY("SELECT VendorAccountNumber, VendorOrganizationName FROM Vendors WHERE VendorGroupId = 'US_SI_VG'")
-> Vendors in a specific vendor group.

=CDATAQUERY("SELECT * FROM VendorInvoiceHeaders WHERE InvoiceStatus = 'Approved'")
-> Approved vendor invoices.

**Using Cell References:**
=CDATAQUERY("SELECT * FROM CustomerInvoiceHeaders WHERE InvoiceAccount = '" & A1 & "'")
-> Invoices for customer account in cell A1.

=CDATAQUERY("SELECT * FROM VendorTransactions WHERE AmountMST > " & B1)
-> Vendor transactions exceeding amount in cell B1.

---

**2. Connection Setup**

Before using CDATAQUERY, the CData Excel Add-in must be configured:

1. Install CData Excel Add-in for Dynamics 365 Finance and Operations (~$500-1000/year license)
2. Open Excel and go to CData ribbon tab
3. Click "Get Data" or "Connect"
4. Select Dynamics 365 Finance and Operations as data source
5. Enter connection details:
   - Organization URL (required): Your D365 Finance environment URL
   - OAuth Client Id (required): Azure AD App Registration Client ID
   - OAuth Client Secret (required): Azure AD App Registration Secret
   - Azure Tenant (required): Your Azure AD Tenant ID
6. Authenticate via Azure AD OAuth2 flow
7. Connection persists for session

**Connection Properties:**
| Property | Description |
|----------|-------------|
| OrganizationUrl | D365 Finance environment URL (e.g., https://yourorg.operations.dynamics.com) |
| OAuthClientId | Azure AD registered app Client ID |
| OAuthClientSecret | Azure AD app secret |
| AzureTenant | Azure AD Tenant ID or domain |
| Schema | Optional: OData schema version |

**Azure AD App Registration:**
1. Register app in Azure Portal > Azure Active Directory > App Registrations
2. Add API Permission: Dynamics ERP > Impersonate user
3. Create Client Secret
4. Note Client ID, Secret, and Tenant ID for connection

---

**3. Dynamics 365 Finance Entities Reference**

**General Ledger:**
| Entity | Description | Key Fields |
|--------|-------------|------------|
| MainAccounts | Chart of accounts | MainAccountId, Name, MainAccountType, DebitCreditDefault |
| LedgerJournalHeaders | GL journal headers | JournalBatchNumber, JournalName, Description, Posted |
| LedgerJournalLines | GL journal lines | JournalBatchNumber, Voucher, AccountDisplayValue, Debit, Credit |
| GeneralJournalAccountEntries | Posted GL entries | LedgerAccount, AccountingDate, TransactionCurrencyAmount |
| TrialBalances | Trial balance view | MainAccountId, OpeningBalance, Debit, Credit, EndingBalance |
| DimensionCombinations | Financial dimensions | DisplayValue, MainAccount, Department, CostCenter |

**Accounts Payable:**
| Entity | Description | Key Fields |
|--------|-------------|------------|
| Vendors | Vendor master | VendorAccountNumber, VendorOrganizationName, VendorGroupId |
| VendorInvoiceHeaders | AP invoice headers | InvoiceId, VendorAccountNumber, InvoiceDate, InvoiceAmount |
| VendorInvoiceLines | AP invoice lines | InvoiceId, ItemNumber, Quantity, UnitPrice, LineAmount |
| VendorTransactions | Vendor transactions | VendorAccountNumber, Voucher, TransDate, AmountMST |
| VendorPaymentJournalHeaders | Payment journals | JournalBatchNumber, PaymMode, BankAccountId |
| VendorPaymentJournalLines | Payment lines | JournalBatchNumber, VendorAccountNumber, AmountCurDebit |

**Accounts Receivable:**
| Entity | Description | Key Fields |
|--------|-------------|------------|
| Customers | Customer master | CustomerAccount, CustomerName, CustomerGroupId, CreditLimit |
| CustomerInvoiceHeaders | AR invoice headers | InvoiceId, InvoiceAccount, InvoiceDate, InvoiceAmount |
| CustomerInvoiceLines | AR invoice lines | InvoiceId, ItemNumber, Quantity, UnitPrice, LineAmount |
| CustomerTransactions | Customer transactions | CustomerAccount, Voucher, TransDate, AmountMST |
| CustomerPaymentJournalHeaders | Receipt journals | JournalBatchNumber, BankAccountId |
| CustomerPaymentJournalLines | Receipt lines | JournalBatchNumber, CustomerAccount, AmountCurCredit |

**Fixed Assets:**
| Entity | Description | Key Fields |
|--------|-------------|------------|
| FixedAssets | Asset master | FixedAssetNumber, Name, FixedAssetGroupId, AcquisitionDate |
| FixedAssetBooks | Asset book values | FixedAssetNumber, BookId, AcquisitionPrice, NetBookValue |
| FixedAssetTransactions | Asset transactions | FixedAssetNumber, TransactionDate, TransactionType, Amount |
| FixedAssetDepreciationProfiles | Depreciation setup | DepreciationProfileId, Method, ServiceLife |

**Budget:**
| Entity | Description | Key Fields |
|--------|-------------|------------|
| BudgetTransactionHeaders | Budget entries | BudgetTransactionCode, BudgetModelId, Date |
| BudgetTransactionLines | Budget lines | MainAccount, BudgetType, TransactionCurrencyAmount |
| BudgetAccountEntries | Budget register | LedgerDimension, Date, TransactionCurrencyAmount |

**Dimensions:**
| Entity | Description | Key Fields |
|--------|-------------|------------|
| FinancialDimensions | Dimension definitions | DimensionName, DimensionDescription |
| FinancialDimensionValues | Dimension values | DimensionValue, Description, IsActive |
| LegalEntities | Companies | DataAreaId, Name, FullPrimaryAddress |
| OperatingUnits | Business units | OperatingUnitNumber, Name, OperatingUnitType |

---

**4. Common Field Reference**

**MainAccounts Fields:**
| Field | Description |
|-------|-------------|
| MainAccountId | Account number |
| Name | Account name |
| MainAccountType | Asset, Liability, Equity, Revenue, Expense, BalanceSheet, ProfitAndLoss |
| DebitCreditDefault | Debit or Credit |
| PostingType | Posting behavior |
| CurrencyCode | Account currency |
| DoNotAllowManualEntry | Whether manual posting allowed |
| IsSuspended | Account suspended flag |

**Vendors Fields:**
| Field | Description |
|-------|-------------|
| VendorAccountNumber | Vendor ID |
| VendorOrganizationName | Vendor name |
| VendorGroupId | Vendor group |
| PaymentTermsName | Payment terms |
| DefaultPaymentMethod | Default payment method |
| TaxExemptNumber | Tax exempt ID |
| OnHoldStatus | Hold status (No, Invoice, All) |
| PrimaryContactEmail | Primary email |
| PrimaryContactPhone | Primary phone |

**Customers Fields:**
| Field | Description |
|-------|-------------|
| CustomerAccount | Customer ID |
| CustomerName | Customer name |
| CustomerGroupId | Customer group |
| PaymentTermsName | Payment terms |
| CreditLimit | Credit limit |
| Blocked | Block status |
| SalesCurrencyCode | Sales currency |
| PrimaryContactEmail | Primary email |
| PrimaryContactPhone | Primary phone |

**VendorInvoiceHeaders Fields:**
| Field | Description |
|-------|-------------|
| InvoiceId | Invoice number |
| VendorAccountNumber | Vendor ID |
| VendorName | Vendor name |
| InvoiceDate | Invoice date |
| DueDate | Payment due date |
| InvoiceAmount | Total amount |
| InvoiceStatus | Draft, Approved, Posted, Paid |
| CurrencyCode | Invoice currency |
| Description | Description |
| PurchaseOrder | Related PO number |
| DataAreaId | Legal entity |

---

**5. Legal Entity / DataAreaId Filtering**

Dynamics 365 Finance is multi-company. Most entities include DataAreaId (legal entity/company code).

**Filter by Legal Entity:**
=CDATAQUERY("SELECT * FROM VendorInvoiceHeaders WHERE DataAreaId = 'USMF'")
-> Invoices for USMF company only.

**Cross-Company Query:**
=CDATAQUERY("SELECT DataAreaId, VendorAccountNumber, SUM(AmountMST) as Total FROM VendorTransactions GROUP BY DataAreaId, VendorAccountNumber")
-> Vendor balances across all companies.

---

**6. SQL Syntax Reference**

**SELECT Statement:**
```sql
SELECT column1, column2 FROM EntityName WHERE condition ORDER BY column LIMIT n
```

**Operators:**
| Operator | Description | Example |
|----------|-------------|---------|
| = | Equals | `WHERE InvoiceStatus = 'Posted'` |
| <> | Not equals | `WHERE OnHoldStatus <> 'All'` |
| > | Greater than | `WHERE InvoiceAmount > 1000` |
| < | Less than | `WHERE NetBookValue < 500` |
| >= | Greater or equal | `WHERE InvoiceDate >= '2024-01-01'` |
| <= | Less or equal | `WHERE DueDate <= '2024-12-31'` |
| LIKE | Pattern match | `WHERE VendorOrganizationName LIKE 'Acme%'` |
| IN | In list | `WHERE MainAccountType IN ('Revenue','Expense')` |
| IS NULL | Null check | `WHERE PurchaseOrder IS NULL` |
| AND | Logical AND | `WHERE InvoiceAmount > 0 AND InvoiceStatus = 'Posted'` |
| OR | Logical OR | `WHERE MainAccountType = 'Asset' OR MainAccountType = 'Liability'` |

**Aggregate Functions:**
| Function | Description | Example |
|----------|-------------|---------|
| SUM() | Sum values | `SELECT SUM(InvoiceAmount) FROM VendorInvoiceHeaders` |
| COUNT() | Count rows | `SELECT COUNT(*) FROM Customers` |
| AVG() | Average | `SELECT AVG(CreditLimit) FROM Customers` |
| MIN() | Minimum | `SELECT MIN(InvoiceDate) FROM CustomerInvoiceHeaders` |
| MAX() | Maximum | `SELECT MAX(InvoiceAmount) FROM VendorInvoiceHeaders` |

**GROUP BY:**
```sql
SELECT VendorAccountNumber, SUM(InvoiceAmount) as Total FROM VendorInvoiceHeaders GROUP BY VendorAccountNumber
```

---

**7. Example Formulas by Use Case**

**Chart of Accounts:**
=CDATAQUERY("SELECT MainAccountId, Name, MainAccountType FROM MainAccounts WHERE IsSuspended = 0 ORDER BY MainAccountId")
-> Active GL accounts.

=CDATAQUERY("SELECT MainAccountId, Name FROM MainAccounts WHERE MainAccountType IN ('Revenue','Expense')")
-> Income statement accounts.

**Trial Balance:**
=CDATAQUERY("SELECT MainAccountId, Name, OpeningBalance, Debit, Credit, EndingBalance FROM TrialBalances WHERE AccountingDate = '2024-12-31'")
-> Trial balance as of year end.

=CDATAQUERY("SELECT MainAccountId, SUM(TransactionCurrencyAmount) as Balance FROM GeneralJournalAccountEntries WHERE AccountingDate BETWEEN '2024-01-01' AND '2024-12-31' GROUP BY MainAccountId")
-> Account balances for the year.

**Accounts Payable:**
=CDATAQUERY("SELECT VendorAccountNumber, VendorOrganizationName, SUM(AmountMST) as Balance FROM VendorTransactions WHERE AmountMST <> 0 GROUP BY VendorAccountNumber, VendorOrganizationName ORDER BY Balance DESC")
-> AP balances by vendor.

=CDATAQUERY("SELECT InvoiceId, VendorName, DueDate, InvoiceAmount FROM VendorInvoiceHeaders WHERE InvoiceStatus = 'Posted' AND DueDate < '2024-02-01' ORDER BY DueDate")
-> Overdue AP invoices.

=CDATAQUERY("SELECT VendorAccountNumber, VendorOrganizationName, COUNT(*) as InvoiceCount, SUM(InvoiceAmount) as Total FROM VendorInvoiceHeaders WHERE InvoiceDate >= '2024-01-01' GROUP BY VendorAccountNumber, VendorOrganizationName ORDER BY Total DESC LIMIT 10")
-> Top 10 vendors by spend.

**Accounts Receivable:**
=CDATAQUERY("SELECT CustomerAccount, CustomerName, SUM(AmountMST) as Balance FROM CustomerTransactions WHERE AmountMST <> 0 GROUP BY CustomerAccount, CustomerName ORDER BY Balance DESC")
-> AR balances by customer.

=CDATAQUERY("SELECT InvoiceId, CustomerName, DueDate, InvoiceAmount FROM CustomerInvoiceHeaders WHERE InvoiceStatus = 'Posted' AND DueDate < '2024-02-01' ORDER BY DueDate")
-> Overdue AR invoices.

=CDATAQUERY("SELECT CustomerAccount, CustomerName, COUNT(*) as InvoiceCount, SUM(InvoiceAmount) as Total FROM CustomerInvoiceHeaders WHERE InvoiceDate >= '2024-01-01' GROUP BY CustomerAccount, CustomerName ORDER BY Total DESC LIMIT 10")
-> Top 10 customers by revenue.

**Fixed Assets:**
=CDATAQUERY("SELECT FixedAssetNumber, Name, AcquisitionDate, AcquisitionPrice, NetBookValue FROM FixedAssets fa JOIN FixedAssetBooks fab ON fa.FixedAssetNumber = fab.FixedAssetNumber WHERE fab.BookId = 'CORP'")
-> Fixed asset register with book values.

=CDATAQUERY("SELECT FixedAssetGroupId, COUNT(*) as AssetCount, SUM(NetBookValue) as TotalNBV FROM FixedAssetBooks GROUP BY FixedAssetGroupId")
-> Asset summary by group.

**Budget vs Actual:**
=CDATAQUERY("SELECT MainAccount, SUM(TransactionCurrencyAmount) as BudgetAmount FROM BudgetTransactionLines WHERE BudgetModelId = '2024' GROUP BY MainAccount")
-> Budget amounts by account.

**Journal Entries:**
=CDATAQUERY("SELECT JournalBatchNumber, Voucher, AccountDisplayValue, Debit, Credit, Description FROM LedgerJournalLines WHERE JournalBatchNumber = '" & A1 & "' ORDER BY Voucher")
-> Journal entry details for batch in A1.

**Vendor/Customer Lookup:**
=CDATAQUERY("SELECT VendorAccountNumber, VendorOrganizationName, PrimaryContactEmail, OnHoldStatus FROM Vendors WHERE VendorOrganizationName LIKE '%" & A1 & "%'")
-> Search vendors by name.

=CDATAQUERY("SELECT CustomerAccount, CustomerName, CreditLimit, PrimaryContactEmail FROM Customers WHERE CustomerName LIKE '%" & A1 & "%'")
-> Search customers by name.

---

**8. Error Handling**

**Common Errors:**
| Error | Cause | Solution |
|-------|-------|----------|
| Connection failed | Invalid credentials | Verify OAuth Client ID, Secret, Tenant |
| Invalid entity | Entity name wrong | Check entity names in section 3 (case-sensitive) |
| Invalid field | Field doesn't exist | Verify field names for that entity |
| Syntax error | SQL syntax issue | Check quotes, operators, parentheses |
| No data returned | Query too restrictive | Broaden WHERE conditions, check DataAreaId |
| Permission denied | Insufficient access | Check Azure AD app permissions and D365 security roles |
| Rate limit | Too many requests | Add delays, use LIMIT clauses |
| 401 Unauthorized | Token expired | Re-authenticate via CData ribbon |

**Debugging Tips:**
1. Start with simple query: `SELECT * FROM EntityName LIMIT 5`
2. Add WHERE clauses incrementally
3. Verify date format: use 'YYYY-MM-DD'
4. String values need single quotes: `WHERE VendorAccountNumber = 'V001'`
5. Entity names are PascalCase and case-sensitive
6. Check DataAreaId (legal entity) filter if no data returns
7. Verify Azure AD app has Dynamics ERP permissions

---

**Final Checklist:**
- What D365 Finance data is needed? (GL? AP? AR? Fixed Assets? Budget?)
- What time frame is required? (Use InvoiceDate, TransDate, AccountingDate filters)
- What legal entity/company? (Use DataAreaId filter)
- What dimensions are needed? (Department, CostCenter, Project)
- Are entity and field names correct? (Case-sensitive, PascalCase)
- Are string values in single quotes?
- Are dates in YYYY-MM-DD format?
- Is LIMIT clause needed for large datasets?
- Is Azure AD authentication current?

---

**Additional Resources:**
- CData D365 Finance Driver: https://www.cdata.com/drivers/d365finops/
- CData Excel Add-in Help: https://cdn.cdata.com/help/FFG/xls/
- D365 Finance OData Reference: https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/data-entities/odata
- D365 Finance Data Entities: https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/data-entities/data-entities
