I have a workbook with 30 tabs of data that all follow the same process:
Go to a tab in the template workbook
Use the Data Import routine to spit out a CSV's data, dumping values on line 7 to start.
Delete line 7 when finished (it's useless headers we don't need)
The problem arises from the Import Text File routine, that needs an array for every single sheet. I end up with 40 lines of code for every sheet and no way to variablize the routine. Here's the first section of a 30-part sub (all have similar structure):
'Use the Get Data routine to dump the csv onto the sheet as text/dates where appropriate, then delete line 7
Sheets("Sheet Alpha info").Select 'explicitly declare which sheet to dump onto
Application.CutCopyMode = False 'this is good programming
'this code section is the Get Data routine run in the UI, turned into VBA
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & ThisWorkbook.Path & "\sheet_alpha.CSV", _
Destination:=Range("$A$7")) 'important on every tab!
'.CommandType = 0 'this is only needed when you use the UI to do the routine, so currently commented out.
.Name = "sheet_alpha" 'could variablize this routine, but signficance of .Name is unknown in Import routine.
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437 'no idea what this actually is. encoding for UTF-8?
.TextFileStartRow = 1
.TextFileParseType = xlDelimited 'not set width
.TextFileTextQualifier = xlTextQualifierDoubleQuote 'yes, well-behaved CSV.
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True 'yes, well-behaved CSV.
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, 2, 2) 'this damn array is why we repeat the code. Need a new array for each sheet.
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
'and now remove the useless header line
Rows("7:7").Select
Selection.Delete Shift:=xlUp
So question is: How can I variablize this routine and make it a single FOR loop that also defines each TextFileColumnDataType array as a text-only array (so, Array() filled with 2s each time)?
Extension: If I wanted the array to read other data types (so an array might be Array(1, 2, 2, 3, 2, 2, 2)), how do I do that?
There are really only 3 variables here: the source file, the destination range, and the array of field types.
You could wrap this code in a sub with those 3 parameters and it should work fine. The only challenge is determining the exact field types for each file (assuming that's important here)
Sub Tester()
'eg - call directly
ImportFromText ThisWorkbook.Sheets("test").Range("A7"), _
ThisWorkbook.Path & "\test.csv", _
Array(2, 2, 2, 2, 2, 2, 2, 2, 2)
'...or from a worksheet table
Dim rw As Range
For Each rw in ThisWorkbook.Sheets("Files").Range("A2:C32").Rows
ImportFromText ThisWorkbook.Sheets(rw.Cells(1).Value).Range("A7"), _
ThisWorkbook.Path & "\" & rw.Cells(2).Value, _
Split(rw.Cells(3).Value, "|")
Next rw
End Sub
Sub ImportFromText(DestRange As Range, filePath As String, arrFieldTypes)
Dim sht As Worksheet, qt As QueryTable
Set sht = DestRange.Worksheet
'clear any previous....
Do While sht.QueryTables.Count > 0
sht.QueryTables(1).Delete
Loop
sht.UsedRange.Clear
Set qt = sht.QueryTables.Add(Connection:="TEXT;" & filePath, Destination:=DestRange)
With qt
'.CommandType = 0
.Name = "sheet_alpha"
.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 = arrFieldTypes
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
DestRange.EntireRow.Delete Shift:=xlUp 'and now remove the useless header line
End Sub
Related
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...
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 _
I open a .txt with Excel, copy it to my .xls file, and run some VBA functions.
When there are zeroes to the left of a number, Excel deletes them and the program fails because the number is in fact a string.
How can I copy them with the zeroes?
When I open the .txt with Excel, it opens without the zeroes, so I cannot format anything at that point.
The .txt is dynamic, as the number of characters of the numbers.
A random example of the .txt content:
H 00013 SUPB4 00551 LEM 2252.554 00548 00540 00
The main code is:
Workbooks.OpenText ThisWorkbook.Path & "\Text.txt", Origin:=xlWindows, StartRow:=1, FieldInfo:=Array(1, 1)
UltLinea = Range("A" & Rows.Count).End(xlUp).Row
Range("A1:Z" & UltLinea).Copy
Hoja1Text = ActiveWorkbook.Name
Workbooks(Hoja1GenDocs).Activate
Worksheets("Hoja1").Range("A1").PasteSpecial xlPasteAll
Application.CutCopyMode = False
Workbooks(Hoja1Text).Activate
ActiveWorkbook.Close Savechanges:=False
Range("A1").Select
I tried modifying the "normal" Style, changing the number to # (text), but when a new file is opened, Excel loses this configuration.
Do not use .OpenText to open the text file. Use the .QueryTable to import the file. For example if you text file looks like this
H 00013 SUPB4 00551 LEM 2252.554 00548 00540 00
Then us this
Option Explicit
Sub Sample()
Dim wb As Workbook
Dim ws As Worksheet
Dim fName As String
Set wb = Workbooks.Add
Set ws = wb.Sheets(1)
fName = ThisWorkbook.Path & "\Text.txt"
With ws.QueryTables.Add(Connection:= _
"TEXT;" & fName, Destination:=ws.Range("$A$1"))
.Name = "tempfile"
.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 = True
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, 2, 2)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
I found this forum while I was trying to sort out my VBA code. I only have very little experience in VBA programming so far. That is why I have researched since two days for a solution for my problem, without success. However, I am very interested in impoving my programming skillsa and I hope you can help me to do so.
Basically I would like to import a TXT file into the active Excel workbook, sheet named "DataImport" at the end of the table named "TblDataImport".
The TXT file consists of 13 columns which are separated by tabs:
row: CompanyName
row: Date Name CustomerGroup CustomerNo SalesOrder ItemNumber ItemGroup LineStatus Quantity Price Discount DiscountPercentage NetAmount
row: All corresponding values...
I dont't need to import the first and the second row since the table where I would like to import the data to aready exists including headings. Also I only need 7 out of the 13 columns, those that are formated in bold. It would be perfect if the user could choose the text file using an open file dialogue.
If I open the TXT file manually and paste its content into Excel, it is already included
in the right columns. So there should not be any pitfalls with regard to formatting.
I am curious about the solutions you come up with.
With the macro recorder I can only fulfil some of my conditions:
Sub DataImport()
' DataImport Makro
Sheets("DataImport").Select
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\Sales.txt", Destination:=Range _
("$A$1"))
.Name = "AxaptaSales"
.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 = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(4, 1, 9, 9, 1, 9, 9, 9, 1, 1, 1, 9, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
However this code only pastes all columns into cell A1 (not at the end of the table). Also it includes the first and second row as well as the columns I don't need.
If you add the following to the code above this will add it to the end of the data already in the worksheet
Sub DataImport()
Dim LastRow As Integer
Dim LastRow2 As integer
LastRow = Range("A65536").end(xlup).row
LastRow = LastRow + 1
' DataImport Makro
Sheets("DataImport").Select
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\Sales.txt", Destination:=Range _
("$A" & LastRow))
.Name = "AxaptaSales"
.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 = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(4, 1, 9, 9, 1, 9, 9, 9, 1, 1, 1, 9, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Range("A" & LastRow & ":A" & LastRow + 1).entireRow.delete
LastRow2 = Range("A65536").end(xlup).row
Range("H" & LastRow & ":M" & LastRow2).entirecolumn.delete
End Sub
I think this should do as you require(But I am still a novice myself)
I have a macro enabled excel workbook that contains several named worksheets. One of the worksheets is named "panel" and a second worksheet is named "data". The sheet named "panel" has a button to which a macro is assigned. I would like to select the button on the worksheet named "panel" and have a browse for file window appear. Once the user selects the csv file on their hard drive, I would like the contents of the csv file to be imported into the worksheet named "data" starting in cell A1.
PROBLEM 1: The vba I have assigned to the button causes the contents of the csv file to be placed on the same worksheet as the button (the "panel" worksheet). I would like the contents of the csv file to be placed on the "data" sheet.
PROBLEM 2: Also, there is a string of code referencing my hard drive and a file called "capture.csv". So when macro enabled excel file is on another computer, the file crashes. Any way to remove the pathway string so any computer could use the file?
Any assistance to fix this issue would be greatly appreciated. The macro assigned to the button follows:
Sub load_csv()
Dim fStr As String
With Application.FileDialog(msoFileDialogFilePicker)
.Show
If .SelectedItems.Count = 0 Then
MsgBox "Cancel Selected"
End
End If
'fStr is the file path and name of the file you selected.
fStr = .SelectedItems(1)
End With
Range("A1").Select
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\laptop\Desktop\CAPTURE.csv", Destination:=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
MsgBox fStr
End With
End Sub
Is this what you are trying?
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:=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
For Excel on Mac, it seems the QueryTable object does not support the properties "PreserveFormatting" and "RefreshPeriod" and will give you a runtime error if you try and set them.
Also, Application.FileDialog does not work with Mac either, but that is covered in other posts.
For Mac:
Sub load_csv()
Dim fStr As String
fStr = "Macintosh HD:Users:anthony:Documents:example.csv" 'Keeping file String simple for example.
With ThisWorkbook.Sheets("Data").QueryTables.Add(Connection:= _
"TEXT;" & fStr, Destination:=Range("$A$1"))
.Name = "CAPTURE"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
'.PreserveFormatting = True **commented out for Mac
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
'.RefreshPeriod = 0 **commented out for Mac
.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