Simplified VBA Code for External Data Source - sql

so in all my VBA macros that use SQL to query our database, I have just been using what is automatically entered when recording a macro in Excel. Is there a way to simplify it? It inserts it into a table first, but really I just want to the raw data in a spreadsheet... it doesn't need to look nice.
Sheets("Sheet1").Select
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:="ODBC;DSN=AS400;" _
, Destination:=Range("$A$1")).QueryTable
.CommandText = strSQL
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_LOCAL_ITEM"
.Refresh BackgroundQuery:=False
End With
ActiveSheet.ListObjects("Table_LOCAL_ITEM").Unlist
Cells.Select
Selection.ClearFormats

I cannot remember the exact code, but can look it up when I get to work again. But depending on which method you use to fetch the data in your SQL (e.g. ADO or DAO), I would do it something like this, if I just wanted the raw data.
If you define a variable as your recordset (for example Dim rst as recordset), VBA has a function to return all data from your recordset, something like:
Sheets("Sheet 1").Range("A1").CopyFromRecordset rst
Which will output all the data from the recordset.

Related

VBA Code to Paste SQL Query in Excel with NULL values pasted as "NULL"

Below is my code to run and post my query results in Excel. The code pastes NULL as 0. I would like the NULLs to be a
pasted as "NULL". I think some type of paste values would work or changing my table from a ".QueryTable" may help. I am not sure what to do. Any suggestions?
'Import Data
With queryOutputWS.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
"ODBC;DRIVER=SQL Server;SERVER=W51SQP-********;Trusted_Connection=Yes;APP=Microsoft Office 2010" _
), Array(";DATABASE=*****")), Destination:=queryOutputWS.Range("A1")).QueryTable
.CommandText = myQuery
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.PreserveColumnInfo = False
.ListObject.DisplayName = "Query"
.Refresh BackgroundQuery:=False
End With
queryOutputWS.ListObjects("Query").Unlist
I think it is easier to change the SQL query rather than the VBA code. If you later post the code of your query I could see if what I'm thinking applies, but nevertheless, you could try this:
Suppose the column you want to query and change the values is called Column1
In your query, change the SELECT [...,] Column1 [,...] FROM ... to:
SELECT [...,] IIF(Column1 IS NULL, 'NULL', Column1) [,...] FROM...
Let me know if that helps!

Auto refresh Pivot tables on data change

I have a worksheet Data which web scrapes a data based on a dynamic link. There is another PivotTable with pivot tables based on the Data worksheet.
Data worksheet uses the following macro and clears the contents of the cells before web scraping new updated data. This data is updated every 1 minute.
I have the following code which will refresh the pivot tables on data update.
ThisWorkbook.Worksheets("PivotTable").PivotTables("PivotTable1").RefreshTable
Since the data takes about 20 seconds to complete updating, there is no data (as the cell contents are cleared first) for the pivot table to refresh. So, I get an error.
Data uses the following code to update data:
With ThisWorkbook.Worksheets("Data").QueryTables.Add(Connection:= _
"<URL redacted>", Destination:=ThisWorkbook.Worksheets("Data").Range("$A$1"))
.Name = "DataPull"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingNone
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=True ' .Delete
End With
I have tried updating the .RefreshStyle = xlInsertDeleteCells to .RefreshStyle = xlOverwriteCells. But it overwrites the cells until the end of the rows of the new data. If new data (number of rows) is less than old data's rows, then the old data rows at the end are not deleted.
I only want the data from the latest update to be kept.
How do I auto refresh the pivot tables based on above conditions?
Just set .BackgroundQuery = False so that your query will be performed synchronously (meaning, it will wait for the data to be loaded before doing the pivot refresh).
Try using a do loop while to wait for the scraping to complete.
Do
Err.Clear
On Error Resume Next
Debug.Print Err.Number
ThisWorkbook.Worksheets("PivotTable").PivotTables("PivotTable1").RefreshTable
Debug.Print Err.Number
Loop While Err.Number > 0

how to import data using .odc file in Excel 2013 VBA

I am trying to write some VBA that will import some data into a query table using a .odc file that is stored in a SharePoint data connection library. I used the macro recorder to record the process where I add the connection, then go to the existing connections and import the data into a table in the current worksheet(which worked when I did it manually).
The recorder spit out the following code (I removed the command text since it contains some sensitive info, but it was a big string of SharePoint related stuff like the list and view GUID):
Sub RecordedImportMacro()
Workbooks("MyWorkbook.xlsm").Connections.AddFromFile _
"http://path/to/my/odcfile/on/sharepoint.odc"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"OLEDB;Provider=Microsoft.Office.List.OLEDB.2.0;Data Source="""";ApplicationName=Excel;Version=12.0.0.0" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = 5
.CommandText = "some command text here"
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.SourceConnectionFile = "http://path/to/my/odcfile/on/sharepoint.odc"
.ListObject.DisplayName = "My_Table"
End With
End Sub
However, when I run the macro to seemingly perform the exact same task that worked before I get the following error: Run time error 1004. I googled and it didn't really find anything that pertained to my use case
when I debug the following line is highlighted: .CommandType = 5
Any ideas on how to get this working?
I was able to get it working using code found here
Below is the code:
Sub ThisWorks()
With ActiveSheet.QueryTables.Add(Connection:= _
"FINDER;http://path/to/my/odcfile/on/sharepoint.odc" _
, Destination:=Range("$A$1"))
.RefreshStyle = xlInsertDeleteCells
.RowNumbers = False
.FillAdjacentFormulas = False
.RefreshOnFileOpen = True
.HasAutoFormat = True
.BackgroundQuery = True
.TablesOnlyFromHTML = True
.Refresh BackgroundQuery:=False
.SavePassword = False
.SaveData = True
End With
End Sub

Excel VBA - Return SQL Data To Excel Table

I am having a little trouble returning SQL data into an Excel table, instead of dropping the data into the cell I specify (when not using a table) it pushes the whole table to the right.
Does anyone know how I can get it to populate the table as I want to make use of splicers etc. to filter the data. I know I could import the data then turn it into a table but if there's a quicker, simpler way then I'd rather that.
Right now the code I'm using is:
With ActiveSheet.QueryTables.Add(Connection:="ODBC;DSN=<dbname>", Destination:=ActiveSheet.Range("A13"))
.CommandText = strSQL
.Name = "Query"
.FieldNames = False
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=False
End With
ActiveSheet.QueryTables(1).Delete
Many thanks in advance.
Dan

Using VBA to Grab Stock Info from the Web

I have been attempting to write a macro that grabs financial information from the internet and pastes it into my macro for further analysis. I have been trying to use a query from one of my existing connections (MSN stock quotes).
with my code (below) I have been able make the query pop up but what I can't figure out how to do is to enter anything into the box that pops up. What I'm basically looking for is how to (after the code I have listed below) tell excel to type in certain values into the box that pops up and click "OK" to run the query.
below is my code that initiates the query box asking for tickers
With ActiveSheet.QueryTables.Add(Connection:= _
"FINDER;C:\Program Files\Microsoft Office\Office12\QUERIES\MSN MoneyCentral Investor Stock Quotes.iqy" _
, Destination:=Range("$A$1"))
.Name = "MSN MoneyCentral Investor Stock Quotes"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlEntirePage
.WebFormatting = xlWebFormattingAll
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = True
.Refresh BackgroundQuery:=False
End With
Sean, have a looksie at VB.NET as opposed to VBA - you'll find it much more conducive to things like this. As for good libraries for financial data - check out this library:
https://code.google.com/p/yahoo-finance-managed/