Using string variable as the Text connection - excel

I am trying to write a script that loops through all the text files in a single directory and import them into Excel worksheet. They are all the same format and file type (.txt).
I have the groundwork in place for the script to successfully loop through all the files, setting the full path of each file in a string variable called FullConnection.
I know the variable is correctly setting the full path of the file because I am showing it in a message box right before where the import should happen.
My question is this:
why does the below code not work for passing in the variable as the connection name?
I'm sure it's something silly I'm doing wrong but can't seem to work it out. Hardcoding a single filepath works fine, so I know it's just the connection variable that is giving me issues.
I've seen the MSDN article on this topic but they don't show how to set a variable as the connection string, only hardcoding the actual path of the text file. Any help is appreciated!
MsgBox fullConnection
'Start importing current file into Excel:
With ActiveSheet.QueryTables.Add(Connection:="TEXT;<fullConnection>", Destination:=Range("$A$1") _
)
.Name = fullConnection
.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 = 4
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
'.Refresh BackgroundQuery:=False
End With

You've enveloped the path variable into the quoted string. You need to concatenate the path variable onto the right end of that quoted string.
ActiveWorkbook.Worksheets.Add
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fullConnection, Destination:=Range("$A$1") _
)
...
I've also added a WorkSheets.Add method that should guarantee that each text file is brought into a new worksheet.

Related

VBA Excel won't copy data to sheets

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.

Convert delimited text to csv

I need to convert the file containing delimiter "|" to excel file using VBA. My code is working when I used the constant path location. But, I got an error if I used the value from the textbox wherein the user will select the location of the file.
Here is my code:
Dim wb As Workbook
Dim File1 As String
Set wb = Workbooks.Add(xlWBATWorksheet)
File1 = txtBox.Text
With wb.ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;File1" _
, Destination:=Range("$A$1"))
.Name = "sample"
.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 = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "|"
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Rows("1:1").Select
Selection.Delete Shift:=xlUp
Rows("2:2").Select
Selection.Delete Shift:=xlUp
The File1 is the location of the file. It can be change depending on the location of the txt file. If I change it to example "C:\Users\sample.txt", it is working fine. Is there anything wrong with my code?
Error:
Also, how can I change the value of .Name using the selected file from the textbox instead of hardcoded it?
Thank you.
Try changing this line:
"TEXT;File1" _
to
"TEXT;" & File1 _

Run Excel macro without opening it

I have a functionality where in I get CSV file as email attachment. I have to import that CSV file into Excel file, build SSRS report on that Excel file. I have written a macro to import data from CSV into Excel. But I want that Excel file should get populated with CSV data without opening because it is not convenient to open Excel file every time to get refreshed SSRS report. I have written VBS code also to run macro but it is not populating my Excel file.
My Macro:
Sub getDataImported()
Sheet11.Cells(1, 1).Resize(1, 3).EntireColumn.ClearContents
MsgBox "Inside Macro"
With Sheet11.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
My VBS:
Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Run "'D:\Sample SSRS\power View\AlertHistory.xlsm'!Module1.getDataImported"
objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing
How did you define "Sheet11" in your code. This should give a compile error since it is not declared? I presume if you tried your code manually, it does not run?
If your sheets name is "Sheet11", than use thisworkbook.worksheets("Sheet11") instead of 'Sheet11'.
The way he used Sheet11 is valid if Sheet11 is a CodeName of one of his sheets. I'm assuming the macro getDataImported works fine by itself and it's the .vbs file that's failing? Is the name of your module Module1 and are you sure your .vbs file is saved with the extension .vbs? Does your "Inside Macro" msgbox show up when you execute your .vbs file?
I'm the author of the website where you got this from (wellsr.com), so I'm happy to help. Idk why the link to the original source page was edited out.

Run-time error when deleting a named range

I don't understand why I keep getting a "Run-time error '1004': Application-defined or Object-defined error" message when trying to delete a named range.
Here's the code used to import data from a .csv file and name the range as "history"
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\<user name>\Downloads\history.csv", Destination:=Range(destCell))
.Name = "history"
.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 = 3
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(3, 1, 2, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Here's the code used to delete the "history" named range. Note that the line immediately before it functions just fine to find the named range. It just doesn't won't delete the name.
Application.Goto Reference:="history"
ActiveWorkbook.Names("history").Delete
Answer: The problem was that the Workbook was using a worksheet name as part of the Name attribute of the named range. Specifically it was using history!history for the name.
Method of Troubleshooting: I used the following code that had been posted to a similar question at http://www.ozgrid.com/forum/showthread.php?t=49079&page=2
Dim nameRng As Name
Dim varVal As Variant
On Error Resume Next
For Each nameRng In ActiveWorkbook.Names
varVal = Range(nameRng.Name).Value
nameRng.Delete
Next
The Locals Window in the VBA Editor revealed that the nameRng.Name for this variable was the string "history!history".
Revised code: I removed the Application.Goto Reference:="history" line since it was essentially a non-functional line of code (similar to a Select action) and was left with this as the code to delete the Name of the Imported range:
ActiveWorkbook.Names("history!history").Delete
Platform: I was using Excel 2013 on Windows 7 Professional

How to Import CSV data into Excel after selecting file from Userform

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

Resources