Excel 2007, VBA import new .csv files to update existing tab - excel

I've just been acquainting myself with the VBA language and would appreciate any help. I'm trying to write a program that updates an existing tab with a new file.
Here's what I have so far:
Sub ImportFile()
'
' ImportFile Macro
'
' Keyboard Shortcut: Ctrl+Shift+I
' Clears active sheet
Cells.Select
Selection.ClearContents
Range("A1").Select
' "Open" prompt window
Dim aFile As String
aFile = Application.GetOpenFilename(FileFilter:="Comma separated values files, *.csv")
If aFile = "False" Then Exit Sub
' Import .csv file to active sheet
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\jiarui.hou.THRUBIT\Desktop\thrubit\data\PS25R_175c_20110711_proc1.csv" _
, Destination:=Range("$A$1"))
.Name = "PS25R_175c_20110711_proc1"
.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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
But the problem is in the first two lines of the third part, it directs to a specific file. But I want the program to import ANY file that I had specifically selected. I guess what I'm asking is how do I link the second part which prompts a window to open a file, to the third part which links that directory address in place of the current SPECIFIC directory address.

Use the concatenation operator & and make the string that you pass to connection be "TEXT;" & aFile
With ActiveSheet.QueryTables.Add(Connection:= "TEXT;" & aFile, Destination:=Range("$A$1"))
Also, I think instead of "False" you want False on the 7th line.

Related

TXT connectivity issue

I Have recoded a code using the Record button.
Basically, I need to remove all special characters using 65001 in File Origin.
I have run a script that converts the .txt in 65001 formats and applies Text to columns as well. Because I need to open .txt data in an excel file
But the problem is the script is run perfectly fine for the 1st TXT file but But for the remaining .txt Text to column function doesn't apply.
Str = "TEXT;" & myFile
With ActiveSheet.QueryTables.Add(Connection:=Str, destination:=Range("$A$1"))
.Name = "UK"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 65001
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=True
End With
I don't know the exact issue. Please find the attahced image as well the formating of 1st and the remainging txt data in excel file.
As you can see in 1st image there is noting after the heading "Letest deleivery date". But for the remain format there are data not perfectly extracted from txt to excel.
Please check and let me know the reason.
Since you're always adding a new querytable, try removing any existing ones first.
Dim Str
Str = "TEXT;C:\Tester\tmp.txt"
'remove any existing querytable(s) and clear associated range
Do While ActiveSheet.QueryTables.Count > 0
With ActiveSheet.QueryTables(1)
Debug.Print "Clearing querytable at ", .ResultRange.Address
.ResultRange.Clear
.Delete
End With
Loop
With ActiveSheet.QueryTables.Add(Connection:=Str, Destination:=Range("$A$1"))
.Name = "UK"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells 'this is better I think
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 65001
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=True
End With

How to import data to an existing worksheet and then overwrite the data on the second import in VBA?

My current workbook is made of a two worksheets: 1) Controls 2) Raw. The "Controls" allow me to press a number of buttons to test processes I am building. I am currently working on importing the data from a text file to the other Excel worksheet "Raw." I recorded a macro importing the text file to the Raw worksheet and got the code. I modified it slightly to create a dynamic file path for any user and commented out one line of code (caused continual errors and couldn't find a good explanation for a fix). I am running into an error I am struggling with (I am not a developer - just learning as I go) The error I get occurs when I try and run the macro from the controls worksheet and send the text file data to the raw worksheet. The notification says:
Run-Time Error '-2147024809 (80079957)': The destination range is not on the same worksheet that the Query table is being created on.
I understand the message (I am not running macro from the Raw worksheet) but I do not know how to fix the code to get it to run.
My second question is, if someone can help with the first problem, how will I have to alter the code, if at all, to have the data contained in "Raw" to be overwritten when I run the testimport macro again?
Sub TestImport()
Dim FPath As Variant
FPath = "TEXT;" & Environ("userprofile") & "\MyFilePath\File.txt"
MsgBox FPath
With ActiveSheet.QueryTables.Add(Connection:= _
FPath _
, Destination:=Range("Raw!$A$1"))
'.CommandType = 0 (Error here has something to do with query table data type - no value will solve so comment out and program runs)
.Name = "File"
.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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
ActiveWindow.SmallScroll Down:=-360
Sheets("Raw").Select
End Sub

How do I modify this code to import text file via FileDialog?

Hi there I am trying to import a text file from a folder based on FileDialog from a set path? I have a code that imports a text file but it only opens up a generic C:\\ path, How should I modify the code below in order to open a folder for a specified path?
Sub ImportTextFile()
Dim fName As String, LastRow As Long
fName = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If fName = "False" Then Exit Sub
LastRow = Range("A" & Rows.Count).End(xlUp).Row + 1
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fName, _
Destination:=Range("A" & LastRow))
.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 = xlTextQualifierNone
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "" & Chr(10) & ""
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Any help would be greatly appreciated!
I did the following alteration to the beginning of the code, but now I get "1004 Application Defined Error"
Sub ImportTextFile()
Dim fName As FileDialog, LastRow As Long
Set fName = Application.FileDialog(msoFileDialogOpen)
fName.InitialFileName = "\\olscmesf003\gcm_emea\TCU_REPORTS\APPS\Reports\Regional\Pointsec for PC Web RH\2017\"
If fName = "False" Then Exit Sub
Using ChDir before opening the file might help. I would comment, but don't have enough reputation so posting here.
e.g.
Sub ImportTextFile()
ChDir "C:/yourpath/folder/etc"
Dim fName As String, LastRow As Long
....

excel vba code to export a Microsoft Excel 97-2003 .xls file

I am trying to open a file from a user specified path using a VBA Function.
When I paste the content of the file to the desired worksheet, it pastes some weird unrecognizable characters in the worksheet. Can anyone figure out what am I doing wrong?
Here is my code:
Sub x_Macro()
'****************Declaring relevant variables****************'
Dim t As Range
Dim path: path = Application.GetOpenFilename("XLS Files (*.xls), *.xls")
Dim cht1 As ChartObject
'Dim button_click As VbMsgBoxResult
Application.ScreenUpdating = False
Sheets(2).Activate
If path = False Then Exit Sub
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & path, Destination:=Range("A1"))
.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 = True
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With

Copying CSV File to Excel Using Recorded Macro

Below code is not working and throwing error
Invalid Procedure call or argument.
This is the recorded macro code for importing CSV file data into Excel file.
Sub CopyCSVtoExcel()
'
' CopyCSVtoExcel Macro
'
'
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\hkum29\Desktop\New folder\data.csv", Destination:=Range("$A$1" _
))
.CommandType = 0
.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 = xlTextQualifierSingleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 _
, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=True
End With
End Sub
As per the MSDN KB QueryTable.CommandType Property (Excel),
You can set the CommandType property only if the value of the QueryType property for the query table or PivotTable cache is xlOLEDBQuery.
And since it is neither, simply comment the line .CommandType = 0 or delete that line.

Resources