I have a table, tbl_SalesData on the tab Sales Data that is populated by a SQL query. There are only three fields in this table, "Item No," "First Day of Posting Month," and "Shipped Qty."
The SQL query populates text dates in the format YYYY-MM-DD. I need to convert those to numerical dates so that Excel can work with them and do some SUMIFS on the data. I have the following code that I think SHOULD work when the table is refreshed, but I can't get it to execute when the table is refreshed.
Any thoughts on why it's not executing when the table is refreshed? I've tried this code as both ThisWorkbook and code for Sheet 9 (Sales Data.) Your help would be most appreciated!
The SQL query populates text dates in the format YYYY-MM-DD. I need to convert those to numerical dates so that Excel can work with them and do some SUMIFS on the data. I have the following code that I think SHOULD work when the table is refreshed, but I can't get it to execute when the table is refreshed.
VBA Code:
Private Sub Workbook_SheetQueryTableAfterRefresh(ByVal Sh As Object, ByVal Success As Boolean)
On Error GoTo ErrorHandler
Dim ws As Worksheet
Dim tbl As ListObject
Dim cell As Range
Dim dateString As String
Dim realDate As Date
' Set the worksheet and table
Set ws = ThisWorkbook.Sheets("Sales Data")
Set tbl = ws.ListObjects("tbl_SalesData")
' Check if the refresh was successful and the sheet is the one we are interested in
If Success And Sh.Name = ws.Name Then
' Loop through each cell in the "First Day of Posting Month" column
For Each cell In tbl.ListColumns("First Day of Posting Month").DataBodyRange
dateString = cell.Value
If IsDate(dateString) And Len(dateString) = 10 And Mid(dateString, 5, 1) = "-" And Mid(dateString, 8, 1) = "-" Then
' Convert the text string date to a real date
realDate = DateSerial(CInt(Left(dateString, 4)), CInt(Mid(dateString, 6, 2)), CInt(Right(dateString, 2)))
' Format the date as MM/DD/YYYY
cell.Value = Format(realDate, "MM/DD/YYYY")
End If
Next cell
End If
Exit Sub
ErrorHandler:
MsgBox "An error occurred: " & Err.Description, vbCritical
End Sub
Any thoughts on why it's not executing when the table is refreshed? I've tried this code as both ThisWorkbook and code for Sheet 9 (Sales Data.) Your help would be most appreciated!