VBA - Update existing excel file with query - vba

I have an excel file and used this code to import data.
https://www.youtube.com/watch?v=sQIImQbEO_Q
Unlike this example my Datafeeds sheet has data already that is formatted in a particular way. If I rerun the Macro, the existing data shifts to the L1 (That is where the second csv ends) and new data is written from A1.
1) I would like to modify the code to replace the existing one overwrite it.
2) Also the existing one has been formatted in a particular way. I wish to retain the formatting.
How can I best modify my code to do this?
This is the code:
Sub AutomateImport()
For rep = 4 To 16
Dim file_name As String
Dim row_number As String
Dim output_sheet As String
file_name = Sheets("Admin").Range("B" & rep).Value
output_sheet = Sheets("Admin").Range("C" & rep).Value
row_number = Sheets("Admin").Range("D" & rep).Value
Sheets(output_sheet).UsedRange.ClearContents
With Sheets(output_sheet).QueryTables.Add(Connection:="TEXT;" + file_name, Destination:=Sheets(output_sheet).Range("$A$" + row_number))
.FieldNames = True
.RowNumbers = True
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Next rep
MsgBox "Done"
End Sub

Related

Import variable path CSV directly into table

I am trying to import data from CSV file "User Roles Entitlements" into my current sheet (current sheet tab name is also "User Roles Entitlements"), which is working perfectly fine if it being imported to cell A1. However, if I try to a table, the code does not work. I know it is a minor tweak, however, I am unable to figure it out.
Note: My file is in the same folder and I am using a variable path import VBA Code.
My code is as follows:
Dim path As String
path = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(ThisWorkbook.path)
Sheets("User Roles Entitlements").Select
Range("A1").Select
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & path & "\User Roles Entitlements.csv", Destination:=Range("A1"))
.Name = "positions_1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 857
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Would appreciate if I could get help with this.
Are you okay if the data connection is lost after you import? In other words, will you need to dynamically refresh the table from the CSV file after you bring it in?
If the answer is no, then you can simply convert the range to a ListObject (table) after the fact.
For ease (so you don't have to figure out the range later), you can capture the range from the QueryTable object before you clobber it.
Sub CsvInsert()
Dim sh As Worksheet
Dim qt As QueryTable
Dim r As Range
Set sh = Sheets("User Roles Entitlements")
Set qt = sh.QueryTables.Add(Connection:="TEXT;" & path & _
"\User Roles Entitlements.csv", Destination:=Range("A1"))
With qt
.Name = "positions_1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 857
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Then convert the querytable to a range and create a table over the range:
Set r = qt.ResultRange
sh.QueryTables("positions_1").Delete
sh.ListObjects.Add(xlSrcRange, r).Name = "positions_1"
End Sub

Importing CSV to another worksheet

I need to import my data into another Excel sheet instead of active worksheet.
I have 2 sheets the UI and the DATA_List. My button is in the UI. I want to import the csv file to data_list sheet.
Sub btnImport_Click()
Dim slect As String
Set r = Range("A" & Cells(Rows.Count, "A").End(xlUp).Row + 1)
With Application.FileDialog(msoFileDialogFilePicker)
.Show
If .SelectedItems.Count = 0 Then
MsgBox "Cancel Selected"
Exit Sub
End If
slect = .SelectedItems(1)
End With
With ThisWorkbook.Sheets("UI").QueryTables.Add(Connection:= _
"TEXT;" & slect, Destination:=r)
.Name = "Data"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Change the first line to
Set r = Worksheets("data_list").Range("A1")
You will also need to change the line
With ThisWorkbook.Sheets("UI").QueryTables.Add(Connection:= _
"TEXT;" & slect, Destination:=r)
To
With ThisWorkbook.Sheets("data_list").QueryTables.Add(Connection:= _
"TEXT;" & slect, Destination:=r)

Excel VBA trouble looping through sheets and calling subroutine

My subroutine works fine when I run it on individual sheets, but I've had a lot of problems getting it to run on each individual sheet. The Subroutine is a simple query of an online CSV database, but it only executes 25 times on the first sheet. can't figure out for the life of me why this is.
I was able to do calculations through this same loop, but could not get it to run a subroutine on each sheet.
Sub Datacollection()
Dim ws As Worksheet
For Each ws In Worksheets
ws.Application.Run "Gethistory"
Next ws
End Sub
Sub Gethistory()
Dim Target As Variant
Dim Name As Variant
'
Set Target = Range("B1")
Set Name = Range("B2")
With ActiveSheet.QueryTables.Add(Connection:= _
"Text;" & Target, _
Destination:=Range("$A$3"))
.Name = Name
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Gather the worksheet to be processed in your primary loop and pass that to the getHistory sub as a parameter.
Option Explicit
Sub dataCollection()
Dim w As Long
For w = 1 To Worksheets.Count
getHistory Worksheets(w)
Next w
End Sub
Sub getHistory(ws As Worksheet)
Dim trgt As Range, nm As Range
With ws
Set trgt = .Range("B1")
Set nm = .Range("B2")
With .QueryTables.Add(Connection:= _
"Text;" & trgt.Value, _
Destination:=.Range("$A$3"))
.Name = nm.Value
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End With
End Sub
If you do this repeatedly, you will end up with a lot of connections that could interfere in the general workbook efficiency as well as future getHistory runs. You might want to delete the connections as you create them or only use a refresh method to maintain the data.

Import multiple CSV files into master excel spreadsheet and append the data to previous imports

I have a script that imports a .csv file into worksheet "Data"
After the first import all following ones appear to the right of the previous imports and not added onto the bottom (last row).
I think the issue involves this area of the script:
Destination:=ThisWorkbook.Sheets("Data").Range("$A$1"))
Sub load_csv()
Dim fStr As String
With Application.FileDialog(msoFileDialogFilePicker)
.Show
If .SelectedItems.Count = 0 Then
MsgBox "Cancel Selected"
Exit Sub
End If
'fStr is the file path and name of the file you selected.
fStr = .SelectedItems(1)
End With
With ThisWorkbook.Sheets("Data").QueryTables.Add(Connection:= _
"TEXT;" & fStr, Destination:=ThisWorkbook.Sheets("Data").Range("$A$1"))
.Name = "CAPTURE"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
You need to examine the destination to see what the next unused cell is.
With ThisWorkbook.Sheets("Data")
.QueryTables.Add(Connection:= _
..., Destination:=.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
'lots of other stuff
End With
You can rereference the ThisWorkbook.Sheets("Data") repeatedly but using a With ... End With statement is easier.

Excel Visual Basic Macro- Selecting data dynamically for a chart?

So, this question is probably fairly stupid, but I'm not too familiar with Excel VBA. Here's my generated Macro code which imports data from a text file and graphs it.
Sub getData()
'
' getData Macro
'
'
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\data.txt", Destination:=Range("$D$3"))
.Name = "data_2"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Range("D3:H4").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlXYScatter
ActiveChart.SetSourceData Source:=Range("Sheet1!$D$3:$H$4")
End Sub
Essentially, because the data inputted from data.txt can be any length, this program does not work; it just goes from D3:H3. I'd like the chart to use the data from D3 to HX, where X is the end of the data row. How would I do this?
Thanks for helping an idiot!
Probably the following will work:
Sub getData()
With ...
....
End With
LastRowColH = Range("H65536").End(xlUp).Row
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlXYScatter
ActiveChart.SetSourceData Source:=Range("Sheet1!$D$3:$H$" & CStr(LastRowColH))
End Sub
HTH!
For these thigs, I like to use a named range using =OFFSET().
See http://www.ozgrid.com/Excel/DynamicRanges.htm or google for "excel dynamic range offset"