Hosting Your Own AI/Local LLM On Your PC (For Free)!

Hosting your own AI local LLM (Large Language Model) can offer several benefits, especially for individuals and organizations looking to leverage advanced AI capabilities while maintaining control and security. Here are some key advantages:

Control and Customization:

  • Tailored Solutions: Customize the model to fit specific business needs, industries, or datasets.
  • Data Privacy: Ensure that sensitive data remains within your control and is not shared with external providers.

Security:

  • Data Security: Protect sensitive information by hosting the model on-premises or in a secure cloud environment under your control.
  • Compliance: Meet regulatory and compliance requirements by having full control over data handling and model deployment.

Latency and Performance:

  • Reduced Latency: Host the model closer to where it is needed, reducing latency and improving response times.
  • Optimized Performance: Fine-tune the model and infrastructure for optimal performance tailored to your specific use case.

Cost Efficiency:

  • Long-term Savings: While initial setup costs can be high, hosting your own model can be more cost-effective in the long run, especially for large-scale deployments.
  • Avoid Vendor Lock-in: Reduce reliance on third-party services and potential vendor lock-in, giving you more flexibility in choosing solutions.

Scalability:

  • Flexible Scaling: Easily scale the model and infrastructure to meet changing demands without relying on third-party providers.
  • Resource Allocation: Allocate resources more efficiently based on your specific needs and budget.

Innovation and Research:

  • Advanced Research: Engage in cutting-edge research and development by leveraging the full capabilities of the model and infrastructure.
  • Experimentation: Conduct experiments and iterate on models without the constraints of third-party services.

Integration:

  • Seamless Integration: Integrate the model with existing systems and workflows more easily, ensuring a cohesive and efficient operation.
  • Custom APIs: Develop custom APIs and interfaces tailored to your specific requirements.

Resilience and Reliability:

  • Uptime: Ensure high availability and uptime by managing the infrastructure directly.
  • Disaster Recovery: Implement robust disaster recovery and backup strategies to protect against data loss and downtime.

By hosting your own LLM, you gain significant control over your AI infrastructure, enabling you to tailor solutions to your specific needs while maintaining security and performance. Read on as we walk through the process together.

Instructions (Windows)

  • Download Ollama. Head on over to ollama.com and download for Windows.
  • Install the application.
host your own local LLM - installation image for Ollama.
  • In the meantime, head over to the models page on the Ollama website and read through them to decide which you would like to install. Each model has a command to install it next to the tags. In the example below, it is ollama run llama3.3; copy this command.
  • Once Ollama is installed, start the application from the Start menu.
  • Open a command prompt (Windows logo key + R, type cmd and hit enter).
  • When the command prompt window opens, paste the command you copied from the model page and hit enter.
  • Close Ollama by typing /bye and hitting enter.
  • Next, download the appropriate version of Docker Desktop for your computer.
  • Go to the Open UI github here and scroll to the installation instructions.
  • Copy the “If Ollama is on your computer” command.
  • Run this command in the command prompt. The package is large and may take several minutes to download and install.
  • After the installation is complete, go to the Docker application and note the open-webui container.
  • In your browser, head to http://localhost:3000/
  • Note: On my machine, I had to stop and restart the Docker container the first time; if you are having an issue, try that first.
  • Select the model at the top.
  • You now have a lovely interface to interact with your model! The possibilities are endless.
bookkeeping template image

Small Business Bookkeeping Template | Excel Spreadsheet | Financial Tracker | Profit & Loss | Income Expense Tracker | Digital Download | TWO FREE BONUSES

bookkeeping template image
bookkeeping template preview

ON SALE! Purchase at a discounted price right via Paypal here on bonbonsguide.com or visit my Etsy Shop!!
https://artofbonbon.etsy.com/listing/4316988571

Transform Your Business Finances in Minutes – Not Hours!
Stop losing sleep over messy finances! This comprehensive bookkeeping template is designed specifically for small business owners, entrepreneurs, and freelancers who want to take control of their money without the headache.

✨ What You Get:
Complete Excel Bookkeeping Template Spreadsheet with 9 pre-built worksheets
Easy Setup Guide – just fill in your business details and go!
Income Tracking for multiple revenue streams (Shopify, Amazon, Etsy, consulting, etc.)
Expense Categories covering all business costs
Monthly Profit Goals with automatic calculations
Annual Overview for tax preparation
Inventory Management system
Materials & Products tracking
Sales Tax calculations

🎯 Perfect For:
Etsy sellers & online shop owners
Amazon FBA sellers
Freelancers & consultants
Service-based businesses
E-commerce entrepreneurs
Anyone tired of shoebox accounting!

💪 Why This Template Works:
✅ Plug & Play Ready – No complex formulas to figure out
✅ Comprehensive Coverage – Income, expenses, profit goals all in one place
✅ Tax-Time Friendly – Organized for easy tax preparation
✅ Scalable – Grows with your business
✅ Time-Saving – Set up once, use all year
✅ Professional – Clean, organized layout

🚀 Benefits You’ll Love:
Save 10+ hours every month on bookkeeping
Never miss a deduction with organized expense tracking
Set and track profit goals monthly
Low stress tax season with organized records
Make better business decisions with clear financial data
Professional presentation for investors or loans

📋 What’s Included:
Setup Sheet – Quick entry of accounts and goals
Income Tracker – Multiple revenue streams
Expense Manager – Add as many categories as you need
Monthly Overview – Profit/loss at a glance
Annual Summary – Year-end totals
Sales Tax Tracking – Breakdown by month
Inventory Tracker – Stock management
Materials Cost – Inventory and cost tracking
Products – Item inventory management

💻 Technical Details:
File Format: Excel (.xlsx) – works with Excel
Instant Download – No waiting!
Lifetime Access – Download anytime
Commercial Use – Use for your business
No Macros – Compatible with all versions of Excel
Compatible with Google Sheets & Numbers, but works best in Excel 🙂

🎁 BONUS #1: Small Business Expense Checklist ($29 Value!)
Don’t leave money on the table! This comprehensive checklist covers 80+ often-missed business deductions that could save you hundreds or even thousands on your taxes.

🎁 BONUS #2: Monthly Financial Review Template ($39 Value!)
Don’t just track your numbers – understand them! This professional template helps you analyze your financial data and create action plans for growth. Turn your bookkeeping into business intelligence!

🔥 LIMITED TIME: Get Organized Today!
Stop procrastinating on your accounting! This bookkeeping template helps many small business owners get their finances organized and profitable.

💬 What Customers Say:
“Finally, a bookkeeping system that actually makes sense! Set up in 15 minutes and saves me hours every month.” – Sarah K.
“Perfect for my Etsy shop. Love how it tracks everything I need for taxes.” – Micah D.
“I wish I had this template when I started my business. Would have saved me so much stress!” – Keiko L.

📞 Questions?
Send a message here on bonbonsguide.com or Etsy if you have any questions about the template!
⚡ Instant Download – Start Organizing Today!

💲 LIMITED TIME OFFER – HUGE SAVINGS WHEN PURCHASING HERE VIA PAYPAL 💲

OR Shop on Etsy: https://artofbonbon.etsy.com/listing/4316988571

free bonuses

🏷️ Tags: bookkeeping template, excel, financial planner, profit loss tracker, income expense sheet, business accounting, etsy seller tools, tax preparation, budget tracker, small business, bookkeeping tool, simple bookkeeping, easy bookkeeping, amazon fba tracker, freelancer finances, entrepreneur tools, business spreadsheet, accounting template, financial organizer, expense tracker, revenue tracker, business planner, digital download

Contact us below with any questions.

← Back

Thank you! Your Message Has Been Sent

Adding Last Refresh Date and Time to Power BI Reporting

A frequent question I have received is “How do I add the last refresh date and time to Power BI reporting?”. Great news, this solution is very simple! The code I provide in this article will allow you to create a source, and then use this in one or more of your visuals so that it’s always clear to you and your end users when the report was last refreshed.

Note: if you need refresh times for your individual sources, one solution would be to add a column with DateTime.LocalNow() and then work a DAX measure off of that once the data from that source is loaded for the first time. Definitely comment below if you would like me to expand on that.

Adding the Refresh Source

You are simply going to add a new source, choose Blank from the menu.

Click Advanced Editor to open up the M code window, then copy in the code below.

Power Query Code (M) – Power BI Last Refresh Date and Time

let
    Source =  #table(type table[Date Last Refreshed=datetime], {{DateTime.LocalNow()}}),
    #"Added Custom" = Table.AddColumn(Source, "Updated", each "Updated "),
    #"Added Custom1" = Table.AddColumn(#"Added Custom", "Custom", each [Updated]&Text.From([Date Last Refreshed])),
    #"Removed Columns1" = Table.RemoveColumns(#"Added Custom1",{"Date Last Refreshed", "Updated"}),
    #"Renamed Columns1" = Table.RenameColumns(#"Removed Columns1",{{"Custom", "LastUpdate"}})
in
    #"Renamed Columns1"
Power Query Last Refresh Date and Time, Power Query M, Power BI Last Refresh Date and Time
Last Refresh Date and Time in Power BI M Language

Click Done. You will notice that I have added the word “Updated” ahead of the date and time in this code. I prefer to display the measure this way in my reporting. If you would prefer to just have the date and time, simply delete the steps after Source in the Query Settings at the right. I find it’s best to work from the bottom, up when removing steps.

Of course, you can also edit the output as you see fit, displaying in the way that works best for your report.

Power Query Last Refresh Date and Time, Power Query M, Power BI Last Refresh Date and Time
Power Query Settings and Steps

Adding the Last Refresh Date and Time to the Report

After Applying the change, you should now see the source and column listed.

Last Update

I find it easiest to add a card visual to display the date and time. Simply select the card visual and then select the LastUpdate column. You can then edit the visual as you see fit for your report.

Card Visual

Final Output

Last Refresh Date and Time Visual in Power BI

As always, I hope this post has helped you out. Please subscribe to be notified of the latest posts and leave a comment if you have any topics you’d like to see covered here. Thanks!

Topics covered in this post: Power Query Last Refresh Date and Time, Power Query M Current Date and Time, Last Refresh Date and Time in Power BI

code execution has been interrupted window

How to Make Excel Wait or Pause in a VBA Macro

When running macros, I have often found the need for an Excel wait or pause, mainly so that other things can happen. DoEvents surely helps for waiting for things to happen within Excel, but sometimes you need to wait for processes to start or finish outside of Excel before moving onto other steps in VBA.

Why Wait?

I am a big fan of automating processes, especially with VBA in Excel. For example, I update and save a spreadsheet to SharePoint that a Power BI model is using. I have a Power Automate process set up that automatically refreshes the Power BI model whenever this particular spreadsheet is updated. The challenge is that Power BI temporary locks the workbook as it reads it, so if I am updating a few times in a short amount of time, Excel needs to wait until the SharePoint file is unlocked.

Also, I have another process where I call a Python script and once that is done, I continue on with VBA code to process the workbook Python outputs. I need Excel to wait while the Python code runs. Side note: let me know if you would like me to write more about these other automated processes. It’s simply amazing what you can get accomplished!

The Solution – Pause in a VBA Macro

Good news – making Excel wait is very easy! Here is the simple code:

Application.Wait (Now + TimeValue("0:00:50"))

This will have Excel wait for 50 seconds since the time is represented as (H:MM:SS). You can adjust as needed.

Bonus

In my code, I don’t need it to wait every time – only when it runs into an issue saving the workbook on SharePoint. Here is how I have set my code using an error handler in my VBA macro.

On Error GoTo waitforupdate

lsc.SaveAs Filename:= _
        "https://sharepoint.com/sites/Reporting/Milestones/Status.xlsx" _
        , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
        
lsc.Close
Exit Sub

waitforupdate:
Application.Wait (Now + TimeValue("0:00:50"))
Resume Next

I hope this helps you! Please comment or reach out if you would like to see other topics covered. I truly enjoy writing about Excel tips and tricks, especially VBA and automation!

Addressed in this post (to help others find this):

  • Pause in a VBA Macro
  • How to pause Excel
  • How to make Excel pause
  • Make VBA pause
  • Make VBA wait
  • Make Excel wait
  • VBA code wait, VBA macro wait
  • VBA code pause, VBA macro pause
  • VBA wait for another application

Referencing an Excel Sheet With An Apostrophe in its Name – Solved!

The Problem – Apostrophes in Sheet Names

You are trying to use a formula to reference an Excel Sheet with an apostrophe in its name and you keep receiving an error message or a #REF! reference error.

The Solution (Very Easy!)

Great news! Simply replace the apostrophe with two apostrophes in your formula. That’s right, two consecutive apostrophes, not a quote. Very simple solution indeed!

Below I provide two examples. You can manually update the name in your formula (or in the cell you are referencing if using an indirect lookup), or if working with many sheet names, you may opt to use the substitute solution shown below (formula displayed in E5).

=substitute(A4,"'","''")

The substitute can be nested in an indirect formula also.

Excel Sheet with an apostrophe solution
Excel Sheet With An Apostrophe Solution

Please comment below on any other challenges you would like for me to cover. I am contemplating doing a quick solution series in this format!

Also, be sure to check out Dose for Excel (click the image below)! Add over 100 functions to Excel to increase your productivity and more!  Disclosure: this is an affiliate link, so I may earn a small commission if you decide to purchase the add-in. Thanks for supporting my blog!

Dose for Excel - +100 Functions

Some topics addressed in this post:
Ref Error in lookup
#REF! Error in lookup
Ref Error in formula
#REF! Error in formula
How to fix ref error in Excel from apostrophe
Apostrophe in Excel sheet name issue



My Poem – An Ode to Excel

Written by Magic AI and I

Oh Excel, you’re a sight to behold
Your powers so vast, your secrets untold
Your formulas and charts, they never grow old
Your uses are vast, your features unfold

Your beauty’s unmatched, your power’s divine
Your data so precise, and figures so fine
From pivot tables to macros, you make life sublime
A spreadsheet maven, your use is so prime

Oh Excel, you make the mundane sublime
Your features so strong, all those bold lines
From tracking expenses to uncovering goldmines
You make the mundane task feel more like a sweet rhyme

Your power and ease, it’s hard to describe
Your talents so numerous, they stretch as far as the eye can see
You make the task of data entry so much less of a chore
So, Excel, my dear partner and friend, I thank you for making my work life, oh so much more

Solution for Power BI Refresh Error in the Web Service

Web Service Power BI Refresh Error When Trying to Refresh On Premises 32-bit Database/Source

I recently worked with a client who is still using an old 32-bit Oracle instance with lots of dependencies. Upgrading is not currently an option. In her Power BI report/model, she is querying several tables in the Oracle database. Unfortunately due to the 32-bit architecture she was not able to schedule her refreshes, even using the desktop gateway.

The Power BI refresh error she received was “Failed to update data source credentials: An error happened while reading data from the provider: ‘Attempt to load Oracle client libraries threw BadImageFormatException. This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed.'”

Workaround for Power BI Refresh Error in Web Service When Trying to Refresh On Premises 32-bit
Power BI Architecture Error

As a result, she found she could only refresh this report using the Power BI desktop client. She would then manually publish to the cloud. This was cumbersome as the data refresh took quite some time, and she needed it done daily. I came up with two solutions for her, both of which we implemented and tried. One proved to better for us, and ultimately she is successfully using this first solution/workaround that I will cover.

Solution #1Export Query Results to CSV and Post on SharePoint

  • So just as the title of the section states, the final workaround was for us to automate the generation of CSV files to ultimately be consumed by Power Query.
  • We did this by using a combination of scripts pulling data via SQL in VBA (Access, Excel) and via SQL in Python. You can pull the data any way you are most comfortable (macros, etc.).
  • The query results are then outputted to the CSV files, which are written directly to SharePoint folders.
  • After all this was set up and the initial files were changed, we then changed the source of the data in Power Query, to now navigate to SharePoint folders and then process the CSV files.
  • It is important to note that you are not required to use CSV files. These made sense in our case due to the amount of data we were working with (generating several very large files nightly). You can write to any supported file format if that works better in your case, as long as you can place it on SharePoint and Power Query can process it.
  • Also as noted we used a separate folder for each unique query. If you are also replacing several queries, you can either do this (write to separate folders) or if you would prefer just one, then utilize different naming convention patterns to filter.
  • Everything is then kicked off via a command line batch script (.bat) using the Windows task scheduler on her desktop to run overnight. We also set up the same script on a colleague’s PC as a backup/for redundancy in case something were to happen, but it is not actively running.
  • After refreshing and publishing the updated report with the new SharePoint sources, I then went into settings in the Web Service and added the credentials there for SharePoint. I saved and kicked off the refresh in the browser.
  • The refresh was successful, so I then set a daily schedule for the web service to refresh automatically. No intervention has been needed since implementation!

Solution #2 – Automate the Power BI Desktop Refresh Process Using Python

  • This method is much less convenient in my opinion, as after it had been implemented, it failed often and required manual intervention several times before we moved on to the other solution.
  • Another caveat is that this solution requires the user to have at least some familiarity with Python (or finding someone with Python knowledge to tap as a support resource).
  • Also, obviously someone needs to install Python, the required package and then set up the automation to run the scripts.
  • Important note – it is possible to install a portable version of Python if you do not have admin rights on the desktop.
  • The package is called pbixrefresher (repo is linked).
  • This gentleman does a great job of walking through setting it up in his YouTube video about it: https://youtu.be/wtXXpicCUlY

I hope this post has been helpful and has maybe given you some ideas on how to proceed if you or an organization you are supporting is facing this same situation with older data sources. Also, I’d love to hear about other solutions if you’ve faced the same issue and handled it differently.

Please reach out with any questions or if you would like to see further coverage of any of the concepts/steps mentioned in this post. I am also available on a limited basis for consulting as my schedule is full as of late (a good thing!). Just fill out the contact form and I will get back to you.

Organize your DAX measures

How To Organize Your DAX Measures in Power BI Folders and Make Finding Them A Breeze

As you progress in Power BI, you will gradually be working with more DAX measures and calculations. As a result, things can easily get cluttered. Today you will learn a few valuable tips and tricks on how to organize your DAX measures for a more efficient workflow. Hopefully this will help you and become a standard practice!

Watch the video for step by step instructions and a full explanation.

To summarize, Reid shows us how to add a new table and move our measures to it so they are together in one place.

He then shows us how to convert this into a folder, and then subsequently create subfolders to further organize your DAX measures in the model. Reid continues on to show us how we can have a measure in multiple locations if it makes sense.

What a great way to manage the measures as they grow in number!

***** Video Details *****
00:00 Introduction
00:33 Root folders
01:32 Subfolders
03:30 Actual Amount VTB

***** Learning Power BI? *****
FREE COURSE – Ultimate Beginners Guide To Power BI – http://portal.enterprisedna.co/p/ultimate-beginners-guide-to-power-bi
FREE COURSE – Ultimate Beginners Guide To DAX – http://portal.enterprisedna.co/p/ultimate-beginners-guide-to-dax
FREE – Power BI Resources – http://enterprisedna.co/power-bi-resources
FREE – 60 Page DAX Reference Guide Download – https://enterprisedna.co/dax-formula-reference-guide-download/
Enterprise DNA Membership – https://enterprisedna.co/membership
Enterprise DNA Online – http://portal.enterprisedna.co/
Enterprise DNA Events – https://enterprisedna.co/enterprise-dna-events-page/

#EnterpriseDNA #PowerBI #PowerBIDesktop #PowerBITutorial #DAX #DAXTutorial

Copy/Paste Is Not Working While Remotely Working – Solved! (Remote Desktop Issue)

I encountered a strange issue where I suddenly could not copy or paste in Windows or any of the Office applications (Excel, Access, Word, Outlook, PowerPoint, etc.) while working remotely. It was quite frustrating as I was pressed for time and needed this critical function to keep working. I then had the idea to stop the utility for the clipboard, effectively restarting it, and that worked!

If your clipboard copy/paste is not working on your remote machine, to save you the same time and frustration, here is how I resolved the issue:

  • Click on Start and type “Run”. Press Enter. (You can also press the Windows Key + R combination to open the Run window).
  • In the Run window, type cmd and press enter or click OK.
  • When the black command prompt window opens, type the following:
  • taskkill /f /im rdpclip.exe
  • Press enter.
  • Close the command prompt (black) window.

By entering this command, you are forcing the shared clipboard to close and restart itself. Hopefully this helps you out!

View Two Tabs at Once in Excel – One Workbook Side By Side

Are you aware that you can view two tabs at once in Excel, side by side for a single Excel workbook/file?  This is especially helpful if you are working with a formula that affects another tab, whether checking for accuracy or troubleshooting.  It’s also great if you are running what-if scenarios such as in a sensitivity analysis and you would like to keep an eye on the values in two tabs.

Adding a second window in Excel to see two tabs at once:

  1. On the menu bar, click View.
  2. Click New Window.
  3. Position the two windows however you’d like.
  4. Note that it is still one file, so both windows will update when you make a change.  You can save from either window.

Alternatively, if you love keyboard shortcuts like I do, simply use this combination: ALT + W, then N.

Open Two Tabs in Excel
View menu for Excel

Here is an example of how it looks for this sample loan calculator file:

Open New Window Side By Side in Excel

Simple solutions are the best! I truly hope this helped you out! Please consider bookmarking this site and subscribing. I add new content often! Thanks!


Also, check out Amazon for some amazing resources: https://amzn.to/3IoE4O4Disclosure: this is an affiliate link, so I may earn a very small commission if you decide to make purchase.  Thanks for supporting my blog!


If I helped you today, please consider leaving a tip via PayPal to help cover blog costs! Thanks!!

Subscribe for more great content!

rank in Access

Rank in Access Query (Sales Ranking)

A common request I get these days is for ranking of sales in Access by region, state and item combination for analysis and space management.  In my business, we have some overlap, where a state can be part of two separate areas or regions, for example Southern CA vs. Northern CA.  It’s helpful for us to show separate rankings for each region and state combo, as the results often tell a different story for each.

The Pass-Through query below enables me to determine the ranking at each of these levels.  By entering as a Pass-Through query, you can utilize the Rank and Partition SQL commands.  After running this query, I bring the data into Excel for further analysis, but this query is a good starting point for any similar analyses.

Here is the full Access pass-through query, color coded for the explanation below:

Select Region, State, Product_ID, SumSaleQ, StoreCount,Rank
FROM (Select Region, State, Product_ID, SumSaleQ, StoreCount, Rank() over (Partition By state, Region Order by SumSaleQ DESC)as rank
FROM (Select s.Region, s.state, m.Product_ID, sum(m.sale_quantity) as SumSaleQ, count(distinct(m.site_num)) as StoreCount
FROM Store_monthly_sales m, FR_Site_Master s
WHERE m.Site_num = s.Site_num AND m.accrual_month in (‘202007′,’202006′,’202005’)
GROUP BY s.Region,m.Product_ID,s.state)
WHERE SumSaleQ >5)
WHERE rank <205
Order by State ASC, Region Asc, Rank Asc

Explanation

Query 1

Diving right in, since we are measuring at multiple levels, we have some nested queries.  Working from the inside out, my first nested query is this one:

(Select s.Region, s.state, m.Product_ID, sum(m.sale_quantity) as SumSaleQ, count(distinct(m.site_num)) as StoreCount
FROM Franchise.Store_monthly_sales m,Franchise.FR_Site_Master s
WHERE m.Site_num = s.Site_num AND accrual_month in (‘202007′,’202006′,’202005’)
GROUP BY s.Region,m.Product_ID,s.state)

Query 2

We then nest that within this query (the WHERE clause is optional – I am dealing with sales in the thousands, and want to exclude items with a sales quantity less than 5.  Note the Rank() over and Partition By Commands here:

(Select Region, State, Product_ID, SumSaleQ, StoreCount, Rank() over (Partition By state, Region Order by SumSaleQ DESC)as rank

FROM

WHERE SumSaleQ >5)

Query 3

The final nesting and main query is selecting the rank from the second query, along with the other pertinent attributes.  The WHERE clause is again optional, I am looking to limit my results to the top 200 results only for each region and state combination. I use 205 as the figure to allow for ties.  The Order by is also optional.  I like to order the results by state, region and then rank ascending.

Select Region, State, Product_ID, SumSaleQ, StoreCount,Rank

FROM …

WHERE rank <205
Order by State ASC, Region Asc, Rank Asc

Full Query (no color coding)

Select Region, State, Product_ID, SumSaleQ, StoreCount,Rank
FROM (Select Region, State, Product_ID, SumSaleQ, StoreCount, Rank() over (Partition By state, Region Order by SumSaleQ DESC)as rank
FROM (Select s.Region, s.state, m.Product_ID, sum(m.sale_quantity) as SumSaleQ, count(distinct(m.site_num)) as StoreCount
FROM Store_monthly_sales m, FR_Site_Master s
WHERE m.Site_num = s.Site_num AND m.accrual_month in (‘202007′,’202006′,’202005’)
GROUP BY s.Region,m.Product_ID,s.state)
WHERE SumSaleQ >5)
WHERE rank <205
Order by State ASC, Region Asc, Rank Asc

Conclusion

I hope this post will help you in your efforts to rank in Access.  It can be a bit of a challenge, but hopefully the breakdown of the steps here will help you achieve your ranking goals.  Please comment any questions, feedback, or what you would like to see next!  Share this post if you feel it would help someone else! 🙂

If I helped you, please consider buying me a coffee via PayPal! Thanks!!

rank in Access

Solved: Pass a Parameter to a SQL Query in Power Query

I’ve done a fair amount of research around dynamic and parameterized queries, specifically around an Excel query parameter, as in trying to pass a parameter to a SQL query in Power Query.  Here’s the very quick and easy way to do this!

This exact solution works in Excel. Creating a dynamic SQL query with a parameter in Excel allows for amazing flexibility. The use cases are endless and can benefit so many types of Excel work across industries – if you are querying any data source, such as a database, even an Access database, then parameterized querying in Excel can truly simplify your workflow. I am going to cover SQL queries specifically, but please comment below if you would like a tutorial on using a parameter with other data sources. Nearly anything is possible!

You can also easily use parameters in Power BI, but the process for creating the parameter itself is slightly different – I will cover that in a future post.  The query construction is the same in most cases though. Please note that this post assumes you are at least moderately familiar with SQL querying and Power Query. Your mileage may vary depending on your situation.

If you found this post because you are encountering a firewall error when incorporating a parameter, skip right on to that section below (click here) for the solution. After much trial and error, I have found a way that works to overcome this issue harnessing the power of query folding. 

The Solution: Passing a Parameter to a SQL Query

In my example, “SParameter” is the name of the parameter I am using, and it represents a store number (retail location identifier). The related field in my SQL table is [Store].

Create the parameter:

  • In any worksheet, add a new table, with a single record and column.  I highly recommend the Header clearly clarifies what the parameter is so there is no confusion in identifying it.
  • Add this table into Power Query by selecting the table, then Data > From Table/Range
  • When the query editor opens, if necessary, change the data type (in my case I need it to be text).  This is important!
  • Right click on the record and select “Drill Down”.  Since you have only a single record, this step will automatically create a parameter.  
  • In the properties, I name this SParameter (you may enter the name of your choice for your parameter).  Note that the name is case sensitive.

This is how the table is situated in my worksheet (1 is the parameter/the value I will change as needed):

This is how it looks in Power Query after all steps above were completed (I named the column from Enter Store: to Store to make it cleaner (this is an optional step):

Open or Add your SQL Server Query in Power Query

Add your query into the Advanced Editor.


let
Source = Sql.Database(“your connection name”, “your database name”, [Query=”

your query goes here

“])


Create the SQL query with your parameter:

Here’s my simple query example to demonstrate how to build the query with the parameter. Please substitute your table name and fields, as well as your parameter name.

With the parameter in the WHERE clause

“Select  * FROM StoreDetail.Store WHERE Store =” &SParameter&”

  • Simply build your unique SQL statement in Power Query following my example above, adding your parameter into the query with quotes and the & (ampersand) sign surrounding the parameter name.
  • Check the results and modify as needed.
  • If your query has no additional clauses or criteria, simply put quotes and one & sign ahead of the parameter, and then one after followed by two double quotes to close the query statement.

 Additional criteria in the WHERE clause

Here is an example where I have additional criteria in mine, filtering on the OpenDate field; after the second quote, add a space and then continue on with the rest of your query.

Select  * FROM Storelist WHERE Store =” & SParameter &” AND OpenDate < GetDate()-365

This is an example of the properly formatted parameter looks in the Advanced Editor in Power Query (I have built out my query further with the Group By clause – this is optional if it doesn’t apply in your case).

If you are running into issues with the query, you may need to add in single quotes surrounding the parameter (inside of the double quotes – “WHERE Store =‘” & SParameter & “‘;”), or possibly # signs surrounding your parameter inside of the double quotes, if your parameter is a date.  You may have to test with and without these depending on your unique scenario.  

If the query is successful, you can proceed with saving it or adding in additional steps in Power Query if you are further filtering or transforming the resulting data you pulled.

BONUS Information – if you are wondering what GetDate() is, this is the MS SQL current system date, so in a way this is technically a dynamic parameter as well.  In my case, the query will only return stores with an open date that is older than 365 days based on today’s date.  You may find this useful for your query as well if you are looking for dynamic dating.

After updating your parameter in the worksheet table, Select Refresh All from the Data menu and your updated query will run and return the results accordingly!

Managing Privacy Levels in Power Query/Excel

VERY IMPORTANT: If you are sharing your workbook with others, you may need to edit the Privacy Levels in order for the queries with parameters to work for them. Read on for these important steps.

In Excel Power Query, there are security measures in place to help prevent data from being shared unintentionally. When combining query sources by using the parameter (a value in your Excel file with a SQL server source), many times this security comes into play.

If other users are having an issue refreshing the query/queries where you have added a parameter into the SQL query, please have them follow these steps. I actually copy and paste this right into an Instructions tab of each of the shared workbooks containing parameters that I create for my clients and for colleagues.

  • Go to Data, click Queries & Connections.
  • Your query list will show up in the panel on the right.
  • Right click any query in the list and choose Edit.
  • A window will open. Click File, then Options and settings.
  • Choose Query Options.
  • Click Privacy, which is on the menu on the left, at the bottom.
  • Select the radio button for the Ignore the Privacy Levels and potentially improve performance option.
  • Click OK to save.
  • Click Close & Load in the Power Query Editor window (at the top) to exit the settings.
Parameter to a SQL query (privacy settings)

Troubleshooting/Alternate Method – Firewall issue

If you run into this dreaded error: “Formula.Firewall: Query ‘SParameter (2)’ (step ‘Filtered Rows’) references other queries or steps, so it may not directly access a data source. Please rebuild this data combination.”, then you will need to use this alternate method.

If you received the firewall error above, you can still use your parameter, but you will instead need to use the parameter as a filter in a subsequent step.  Now you may be possibly thinking – my table has thousands (or even millions) of records and I don’t want them all pulling in – don’t worry, this is the beauty of the query folding process when it works properly in Power Query.

Without the parameter in the WHERE clause

Select * FROM StoreDetail.Store WHERE OpenDate < GetDate()-365

  • Write your SQL statement in Power Query as noted above.
  • When the Query Editor returns the columns and record sampling, for the field you will be using your parameter, filter with any single value (Text Filters > Equals). This is simply a placeholder, to create the Power Query M formula for the next step.
  • You will now see that filtering in the formula bar. 
  • Replace the placeholder value with the name of your parameter, removing any quotes from the placeholder.  This is how it looks for me: = Table.SelectRows(Source, each [Store] = SParameter).
  • Power Query is smart enough to modify its native query to use the parameter, so it’s not going to pull in the millions of records and then filter after the fact.  Success!!  This is the power of Query Folding!

Why Can’t You Include the Parameter in the SQL Statement?

In the SQL statement, in most cases we will want add the store number/SParameter as part of the criteria in the select statement.  It may seem counter intuitive, but we cannot always successfully put the parameter directly into the SQL code/query. The challenge is that you are combining data sources and at this time, this is not allowed due to the built in security (SParameter portion is local, SQL portion is external).  Unfortunately some organizations have policies that disallow this. Sometimes it is an Excel version issue.

I truly hope this post helped you out.  If so, please feel free to leave a comment below letting me know so, and if you’d like, add what you’d like me to cover in a future post. Also, feel free to share this with someone else who may find it useful.

Do You Need Personalized Help and Custom Solutions?

If you get stuck or you would like to explore solutions and automation possibilities, please can reach out to me for help as I do offer consulting services as time allows.  I have over 20+ years’ of expert level experience delivering excellent, custom, strategic solutions in Excel, BI, Access, SharePoint and more. 

I have been called a guru and hero more times than I can count, as I am a great listener and truly have a knack for asking the right questions to understand unique business challenges. I am very passionate about crafting tools and processes that work for users of all levels and experience. 

Reach out today and let’s discuss how I can help you and your business!

I also offer one-on-one tutoring for customized learning and upskilling. Visit my consulting page and send a message if you are interested.

Other Excel Resources

Also, consider checking out some great Excel resources on Amazon Disclosure: this is an affiliate link, so I may earn a small commission if you decide to make a purchase, which will help cover the cost of hosting this website. 

Please bookmark and subscribe!  I am actively working on adding new, relevant content to help others out! Thanks so much!

Subscribe via Email and Stay Up to Date!

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Buy Me A Coffee/Support the Blog 🙂

If I helped you, please consider leaving a tip via PayPal to support the blog! Thanks!!

Thanks so much for supporting my blog and for helping others too!