I am trying to write a piece of VBA code, that when a cell value changes by entering a path and a filename, an external query is updated with the filename and path and will run if a parameter is changed.
The code I have is as follows:-
Sub auto_open()
' Run the macro DidCellsChange any time a entry is made in a
' cell in Path_and_Filename.
ThisWorkbook.Worksheets("Path_and_Filename").OnEntry = "DidCellsChange"
End Sub
Sub DidCellsChange()
Dim KeyCells As String
' Define which cells should trigger the KeyCellsChanged macro.
KeyCells = "B1:B3"
' If the Activecell is one of the key cells, call the
' KeyCellsChanged macro.
If Not Application.Intersect(ActiveCell, Range(KeyCells)) _
Is Nothing Then KeyCellsChanged
End Sub
Sub KeyCellsChanged()
Dim sFilePath As String
Dim SFilePathandName As String
sFilePath = Range("Path_and_Filename!$B$1")
SFilePathandName = Range("Path_and_Filename!$B$3")
For Each oWorksheet In ThisWorkbook.Worksheets
For Each oQueryTable In oWorksheet.QueryTables
oQueryTable.Connection = "ODBC;DSN=Excel Files;DBQ=" & SFilePathandName & ";DefaultDir=" & sFilePath & ";DriverId=790;MaxBufferSize=2048;PageTimeout=5;"
Next
Next
sFilePath = Range("B3").Value
SFilenameandPath = Range("B1").Value
End Sub
Whenever the code tries to run, I get an error message of macro DidCellsChange cannot be found.
I am a newbie to VBA and the code above has been put together from code I have got from various websites, so hopefully it will be something simple?
I have attached the workbook as an example. The sheet Path_and_Filename contains the cells where the path and filename can be entered. When these cells have been updated, then the sheet named Query, has a parameter query that when a day is selected in cell A1, the query runs and returns values in cells A1 to A5. The query will only work if the values entered on the Sheet Path_and_Filename correspond to where the file 'Internal Query with Macro1.xls' is saved.
Bookmarks