VBA Excel won't copy data to sheets - excel

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.

Related

Create new sheets and then import three txt files into their own columns

So backstory, I am currently copying and pasting three .txt files into their own columns per sheet. However, I have a mass amount of data so copying and pasting three .txt files into their own columns per sheet is time consuming. When I right clicked on the sheet to delete it, I saw the button "View code". In astonishment, I see an opportunity to automate this process to save tons of time. I see a vision of
specifying pathnames to the .txt files I am copying and pasting
specifying which column to paste the entire content of the .txt file
With that said, here is an example of what I would like to accomplish using the VBA system in Excel
Starting off, here are 9 .txt files that would be imported into the Worksheet:
TxtFile1Sheet1.txt
Cow1
Rabbit1
Deer1
Crab1
Goat1
Ducks1
TxtFile2Sheet1.txt
Vegetables1
Eggs1
Meat1
Poultry1
Fish1
Seeds1
TxtFile3Sheet1.txt
Fiction1
Narrative1
Novel1
Thriller1
Mystery1
Poetry1
TxtFile1Sheet2.txt
Cow2
Rabbit2
Deer2
Crab2
Goat2
Ducks2
TxtFile2Sheet2.txt
Vegetables2
Eggs2
Meat2
Poultry2
Fish2
Seeds2
TxtFile3Sheet2.txt
Fiction2
Narrative2
Novel2
Thriller2
Mystery2
Poetry2
TxtFile1Sheet3.txt
Cow3
Rabbit3
Deer3
Crab3
Goat3
Ducks3
TxtFile2Sheet3.txt
Vegetables3
Eggs3
Meat3
Poultry3
Fish3
Seeds3
TxtFile3Sheet3.txt
Fiction3
Narrative3
Novel3
Thriller3
Mystery3
Poetry3
Here is the VBA workspace that I want to use to import these txt files to their own columns.
Sub ImportThreeTxtFiles()
'
' ImportThreeTxtFiles Macro
' Import three txt files into three columns per sheet
'
'
Application.CutCopyMode = False
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;/Users/MyName/Documents/TxtFile1Sheet1", _
Destination:=Range("$A$2"))
.Name = "TxtFile1Sheet1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.RefreshPeriod = False
.TextFilePromptOnRefresh = False
.TextFilePlatform = 10000
.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("B2").Select
Application.CutCopyMode = False
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;/Users/MyName/Documents/TxtFile2Sheet1", _
Destination:=Range("$B$2"))
.Name = "TxtFile2Sheet1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.RefreshPeriod = False
.TextFilePromptOnRefresh = False
.TextFilePlatform = 10000
.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("C2").Select
Application.CutCopyMode = False
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;/Users/MyName/Documents/TxtFile3Sheet1", _
Destination:=Range("$C$2"))
.Name = "TxtFile3Sheet1"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.RefreshPeriod = False
.TextFilePromptOnRefresh = False
.TextFilePlatform = 10000
.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
End Sub
Using this Macro I recorded, I want to import these files into their own sheets. How could I specify the three sets of files I will paste in a form of a loop? As in:
FileSet1 = TxtFile1Sheet1.txt, TxtFile2Sheet1.txt, TxtFile3Sheet1.txt
FileSet2 = TxtFile1Sheet2.txt, TxtFile2Sheet2.txt, TxtFile3Sheet2.txt
FileSet3 = TxtFile1Sheet3.txt, TxtFile2Sheet3.txt, TxtFile3Sheet3.txt
These columns will be named Animals, Type of Foods, Genres
Here is the desired output:
I am very new to VBA, I have more of a background in Python. This example is meant to be more conceptual. How would I be able to loop or call these files into these three columns? I'd love to see how the community tackles this to learn from it. I am currently watching videos and reading more about it. Thanks!
Please, test the next code and send some feedback. Take care of using the real folder path where the text file exist:
Sub ImportTextFilesInColumns()
Dim wb As Workbook, sh As Worksheet, strFoldPath As String
Dim fileName As String, shName As String, colNo As Long, arrHd, arrTxt
Set wb = ActiveWorkbook ' you can set here the workbook you need
arrHd = Split("Animals, Type of Foods, Genres", ", ") 'put the headers string in an array
strFoldPath = "Your real folder path" 'place here the folder path where the text file exist
'some optimization: _________________________________________________
Application.ScreenUpdating = False: Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'____________________________________________________________________
'Place the header on the necessary sheets:
For Each sh In wb.Sheets
Select Case sh.Name
Case "Sheet1", "Sheet2", "Sheet3"
sh.Range("A1:C1").value = arrHd
End Select
Next
'iterate between all text files in strFolder:
fileName = dir(strFoldPath & "\*.txt")
Do While fileName <> ""
colNo = CLng(Mid(fileName, 8, 1)) 'extract column number
shName = Mid(fileName, 9, 6) 'extract sheet name
'place the content of the text file in an array:
arrTxt = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile(strFoldPath & "\" & fileName, 1).ReadAll, vbCrLf)
wb.Sheets(shName).cells(2, colNo).Resize(UBound(arrTxt) + 1, 1) = Application.Transpose(arrTxt) ' drop the array content
fileName = dir() 'continue the iteration between files
Loop
Application.ScreenUpdating = True: Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
MsgBox "Ready..."
End Sub
No error handling in case of no sheet with the name extracted from the last 6 digits of the text file (before .txt). You must be atentive when build the txt files name. Such an error handling can be imagined, but not treated in the above code...

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

Excel Macro - Run open file dialog box if no file selected

I have a Macro (below) that opens the dialog box to choose a file and opens it into the 'Invest' sheet, then runs a macro to breakdown the Invest file to selected data
However, If somebody press's cancel or closes the dialog box the macro to breakdown the Invest sheet still runs.
Can somebody help me stop this bug, So if no file is selected the breakdown macro won't run?
Sub Import()
' Imports file '
Application.ScreenUpdating = False
Dim WS As Worksheet, strFile As String
Set WS = ActiveWorkbook.Sheets("Invest")
strFile = Application.GetOpenFilename("Text Files (*.csv),*.csv", , "Please selec text file...")
With WS.QueryTables.Add(Connection:="TEXT;" & strFile, _
Destination:=WS.Range("A1"))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
' Imports file '
'''''''
'RUN MACRO CODE HERE
'''''''
End Sub
I think the error handling your looking for goes something like this:
Dim fn As String
fn = Application.GetOpenFilename("All Files,.", 1, "Select a file", , False)
If fn = "False" Then
Exit Sub
End If
This comes from another Stackoverflow page here
Excel VBA Open File (error handling)

Label sheets while importing multiple text files Excel VBA

I've been attempting to import multiple large text files onto multiple spreadsheets within the same workbook. Thanks to other posts on this site, I have cobbled together some VBA code that seems to do the job. Only problem is that since the data are unlabelled within the text files, it is difficult to tell them apart for analysis. As such, I would like to label each spreadsheet with the corresponding text file during the import process. The code I'm using is as follows.
Thanks!
Sub ImportManyTXTs()
Dim strFile As String
Dim ws As Worksheet
strFile = Dir("I:\test\*.txt")
Do While strFile <> vbNullString
Set ws = Sheets.Add
With ws.QueryTables.Add(Connection:= _
"TEXT;" & "I:\test\" & strFile, Destination:=Range("$A$1"))
.Name = strFile
.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 = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1)
.TextFileFixedColumnWidths = Array(7, 9)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
strFile = Dir
Loop
End Sub
Edit: Managed to figure it out. Just added ws.Name = strFile after End With. Seems to work quite well.
Managed to figure it out. Just added ws.Name = strFile after End With. Seems to work quite well.

In Excel-VBA .how to save a xml file in the existing sheet without saving it any drives

Please check below code... Here I dont want converted xml code to save in any drive, Instead I want to put the contents of converted file into the next sheet of existing excel.
Sub GenerateXML()
'
' GenerateXML Macro
'
'
Sheets("Sheet2").Select
ActiveWorkbook.XmlMaps("result_Map").Export URL:="D:\temp3.xml"
Sheets.Add After:=Sheets(Sheets.Count)
With ActiveSheet.QueryTables.Add(Connection:="TEXT;D:\temp3.xml", Destination:=Range("$A$1"))
.Name = "temp3"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1252
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(2, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
' Kill "C:\temp.xml"
End Sub
Instead of using XmlMaps.Export method, msdn says the following:
Use the ExportXml method to export the contents of the mapped cells to a String variable.

Resources