I am opening a large text file into excel sheet using VBA macro. However, my requirement is to only import few specific rows into the excel sheet which match a particular column values. As an example,
Name Age
--------------
A1 20
A2 21
A3 20
A4 21
A5 22
A6 22
So, I wanted to import with criteria Age = 20 or 21. However, I do not want to use AutoFilter. I just wanted the vba to select the rows that match my filter and display them and ignore all the others. I used autofilter, but it is loading the whole data and showing only the rows of my interest.
The code that I wrote
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" + full_path, Destination:=Range( _
"A1"))
.Name = file_name
.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 = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Range("A1").Select
Can you please help?
you can export data using the option get external data > from other sources > from microsoft query where you have to do few more actions to set up your text file as source, but once done you can add it as a connection which includes filters prior to populating onto the spreadsheet. you can read up more about how to set it up here: About using Microsoft Query to retrieve external data
Related
I'm running a web query for an Excel sheet and have been able to collect data from the website Yahoo-finance. However, instead of having numbers in every cells concerning the stock price of a ticker, my Excel sheet is filled with text and numbers. For instance,the result is the following :
Date close
August 7, 2019 2.015 (correct)
August 6, 2019 févr.50 or 01.02.3750 (wrong -> right data is 2.375 )
August 5, 2019 janv.00 or 01.01.98 (wrong -> right data is 1.98)
Please find below my code. Could you please advise me how I must change my code? Many thanks in advance for your help.
Dim url As String
url = "URL;https://finance.yahoo.com/quote/BALYO.PA/history?period1=1496959200&period2=1565128800&interval=1d&filter=history&frequency=1d"
With Worksheets("Sheet1").QueryTables.Add(Connection:=url, Destination:=Worksheets("Sheet1").Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileCommaDelimiter = True
.Refresh BackgroundQuery:=False
End With
Your same code, without text formatting:
Sub test()
Dim url As String
url = "URL;https://finance.yahoo.com/quote/BALYO.PA/history?period1=1496959200&period2=1565128800&interval=1d&filter=history&frequency=1d"
With Worksheets("Sheet1").QueryTables.Add(Connection:=url, Destination:=Worksheets("Sheet1").Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.Refresh BackgroundQuery:=False
End With
End Sub
It is reporting:
With a header I already hide.
I'm trying to copy the data from a hand full of CSV files into separate sheets of an excel file. I want to create one sheet per CSV file and I would like to delete the sheets if they are already present before copying over the new data (this Part seems to work fine).
Unfortunately my script doesn't seem to copy the data. The script runs without giving me an error but there still is no data in the respective tables.
Leaving out the last bit that deletes the established connection doesn't change anything.
Thank you so much in advance.
The sheet "import" looks like this:
ColumnA ColumnB
file_name sheet_name
<pathTo>\1.csv file_1
<pathTo>\2.csv file_2
<pathTo>\3.csv file_3
<pathTo>\4.csv file_4
My Macro looks like this:
Sub AddAllFiles()
Dim inputRow As Integer
For inputRow = 3 To 20
Dim fileName As String
Dim outputSheet As String
fileName = Sheets("import").Range("A" & inputRow).Value
outputSheet = Sheets("import").Range("B" & inputRow).Value
Dim checkSheetName As String
On Error Resume Next
checkSheetName = Worksheets(outputSheet).Name
If checkSheetName <> "" Then
Sheets(outputSheet).Delete
End If
Worksheets.Add.Name = outputSheet
With Sheets(outputSheet).QueryTables.Add(Connection:="TEXT" & fileName, Destination:=Sheets(outputSheet).Range("$A$1"))
.FieldName = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePlatform = 65001
.TextFilePromptOnRefresh = False
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileConsecutiveDelimiter = True
.TextFileSemicolonDelimiter = True
.TextFileTabDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.PreserveColumnInfo = True
End With
Dim wb_connection As WorkbookConnection
For Each wb_connection In ActiveWorkbook.Connections
If InStr(fileName, wb_connection) > 0 Then
wb_connection.Delete
End If
Next wb_connection
Next inputRow
MsgBox "Imported CSV Files"
End Sub
I changed your setup and used the Refresh function. See below. I also added the semicolon to the Connection string.
The Refresh method causes Microsoft Excel to connect to the data source of the QueryTable object, execute the SQL query, and return data to the range that is based on the QueryTable object. Unless this method is called, the QueryTable object doesn't communicate with the data source.
Therefore, the connection exists but it has not yet attempted to open connection.
Also, this method can fail. If you had left the code without the "TEXT;", you may have received an error. Just something to think about. You may want to do some error handling around it.
After the database connection is made, the SQL query is validated. If the query isn't valid, the Refresh method fails with the SQL Syntax Error exception.
With Sheets(outputSheet).QueryTables.Add(Connection:="TEXT;" & fileName, Destination:=Sheets(outputSheet).Range("$A$1"))
.CommandType = 0
.RefreshPeriod = 0
.Name = outputSheet
.FieldName = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.Refresh BackgroundQuery:=True ' This is the step I changed.
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePlatform = 65001
.TextFilePromptOnRefresh = False
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileConsecutiveDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileTabDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.PreserveColumnInfo = True
.PreserveColumnInfo = True
End With
After Semicolon to "TEXT" (thanks GibralterTop)
With Sheets(outputSheet).QueryTables.Add(Connection:="TEXT;" + fileName, Destination:=Sheets(outputSheet).Range("$A$1"))
and adding
.Refresh BackgroundQuery:=False
right before the end of the with-section my problem seems to be fixed. Since I'm brand new to VBA maybe someone can enlighten me the the exact error was.
I have this code to import a .txt file to my Excel sheet (Sheet1). In Sheet1 I have the first column with a formula, so I import my text data into B1.
This code does it well the first time, however the following ones adds a column to the right, moving the selected cells in the formula of column A. The data is copied in B1 still, but somehow adding a column first. Any help?
Sheets("Sheet1").Select
Columns("B:F").Select
Selection.ClearContents
Dim Ret
Ret = Application.GetOpenFilename("Text Files (*.txt), *.txt", Title:="Select text file(.txt)")
If Ret <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=Range("$B$1"))
.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, 2)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End If
Change
.RefreshStyle = xlInsertDeleteCells to .RefreshStyle = xlOverWriteCells, then run the macro just once. After that you can simply have Excel do the work by hitting the refresh data button on the data tab and get rid of the macro.
See: http://jkp-ads.com/articles/importtext.asp
I have written macro to import three columns from csv file to excel file which has 4 columns. 1 column is formulated based on 3 coming from csv file. So before running macro, there is excel file with 3 blank columns(not even column name) and 4th column with default values. Now when I run the macro, 3 columns are getting imported frm csv but 4th column is getting deleted.I don't know why this is happening. I have used Record Macro functionality to create macro. Below is my macro code:
Private Sub Workbook_Open()
Sheet11.Cells.ClearContents
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;D:\Sample SSRS\power View\AlertHistory.csv", Destination:=Range("$A$1") _
)
.Name = "AlertHistory"
.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)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Please help.
You are clearing the entire worksheet with,
Sheet11.Cells.ClearContents
The 'default values' in the fourth column are going to be deleted along with everything else. If you only want to clear columns A through C and leave the 'default values' in column D then change that line to,
Sheet11.Cells(1, 1).Resize(1, 3).EntireColumn.ClearContents
This will not clear the entire worksheet; only columns A:C.
I need to be able to import column data from a Comma Delimited Excel Sheet into a new sheet using the get external data function. I wish to originally select the file in a userform but cannot figure out how to mate the file selected in the userform with the Import Command. Code for the import module is attached.
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\---\Rainflow Data\J-Rain Outputs\Moment(N-mm).csv" _
, Destination:=Range("$A$1"))
.CommandType = 0
.Name = "Moment(N-mm)"
.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)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Instead of referencing the file path that I selected when recording this macro I need it to open the file I select in the userform. Any help would be greatly appreciated.
Thanks
Assuming the variable yourFilePath has the path to the selected file you can do this:
With ActiveSheet.QueryTables.Add(Connection:= "TEXT;" & yourFilePath, _
Destination:=Range("$A$1"))
.CommandType = 0
.Name = "Moment(N-mm)"
.FieldNames = True
.RowNumbers = False
'etc