CodexBloom - Programming Q&A Platform

VBA: How to dynamically filter a chart based on a user-selected date range from an Excel userform?

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
vba excel chart userform

I'm refactoring my project and I'm attempting to create a userform in Excel VBA that allows users to input a start and end date for filtering data on a chart. The requirement is to display only the data points that fall within this date range. However, I'm running into an issue where the chart does not update dynamically when I change the dates. I currently have a ComboBox for selecting the start date and another for the end date, but the chart isn't reflecting the filtered data accordingly. Here's a simplified version of what I've implemented: ```vba Private Sub btnFilter_Click() Dim startDate As Date Dim endDate As Date Dim ws As Worksheet Dim chartData As Range Dim filteredData As Range Set ws = ThisWorkbook.Sheets("Data") startDate = CDate(Me.cboStartDate.Value) endDate = CDate(Me.cboEndDate.Value) ' Assuming data is in column A (dates) and B (values) Set chartData = ws.Range("A2:B100") ' Filter the data based on the selected dates On Error Resume Next ws.AutoFilterMode = False chartData.AutoFilter Field:=1, Criteria1:=">=" & startDate, Criteria2:="<=" & endDate ' Set filtered data range Set filteredData = chartData.SpecialCells(xlCellTypeVisible) ' Update the chart's data source With ThisWorkbook.Sheets("Chart").ChartObjects("Chart 1").Chart .SetSourceData Source:=filteredData End With On Error GoTo 0 End Sub ``` I'm encountering an issue where I'm getting a runtime error 1004 when trying to update the chart with the filtered range. It seems that `filteredData` sometimes does not contain the expected range of visible cells, especially if there are no rows that match the filtering criteria. How can I ensure that the chart updates correctly, and is there a better way to handle cases where no data is found? I've also tried checking if `filteredData` is `Nothing` before trying to set the chart's source data, but it seems to be more about how I am filtering the data. Any best practices or alternative approaches would be appreciated! For context: I'm using Vba on Ubuntu. Any ideas what could be causing this? Any advice would be much appreciated. Any examples would be super helpful. This is for a microservice running on CentOS.