1
votes

I have tried the below code to import csv file to an excel sheet (Courtesty:http://investexcel.net/download-finviz-data/) and it is working fine. After importing the data, data type was not proper. Please see the screenshot.

enter image description here

The zero prefix was removed 2nd column after importing into excel. Is there any property like '.TextFileColumnDataTypes' for QueryTables.Add(Connection:="URL;"... ?

Sub GetWebCsvData()

Dim str As String
 Dim myarray() As Variant
'Delete existing data
Sheets("Data").Activate 'Name of sheet the data will be downloaded into. Change as required.
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents


str = "http://somedomain.com/filename.csv"
QueryQuote:
            With Sheets("Data").QueryTables.Add(Connection:="URL;" & str, Destination:=Sheets("Data").Range("a1"))
                .BackgroundQuery = True
                .TablesOnlyFromHTML = false
                .Refresh BackgroundQuery:=False
                .SaveData = True

            End With

Sheets("Data").Range("a1").CurrentRegion.TextToColumns Destination:=Sheets("Data").Range("a1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, other:=True, OtherChar:=",", FieldInfo:=Array(1, 2)

Sheets("Data").Columns("A:B").ColumnWidth = 12
Range("A1").Select

End Sub
1

1 Answers

2
votes

This worked quite nicely:

Option Explicit

Sub TestMe()

    Dim filePath As String: filePath = "C:\\file.csv"        
    Cells.Delete

    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & filePath, _
                                                      Destination:=Range("A1"))
        .Name = "test"
        .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 = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 2, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False            
    End With        
End Sub

The correct property is .TextFileColumnDataTypes = Array(1, 2, 1, 1, 1, 1, 1, 1, 1, 1). The 2 in the array stands for Text:

enter image description here