使用具有精确数据格式的VBA从Web文件导入Excel文件

时间:2018-06-12 10:54:57

标签: excel vba excel-vba

我已经尝试了以下代码将csv文件导入excel表(Courtesty:http://investexcel.net/download-finviz-data/),它运行正常。导入数据后,数据类型不正确。请看截图。

enter image description here

导入到excel后,第二列删除了零前缀。 是否有任何属性,如' .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 个答案:

答案 0 :(得分:2)

这非常有效:

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

正确的属性是.TextFileColumnDataTypes = Array(1, 2, 1, 1, 1, 1, 1, 1, 1, 1)。数组中的2代表Text:

enter image description here