簡體   English   中英

使用VBA以准確的數據格式將CSV文件從Web導入到Excel工作表

[英]CSV file import to excel sheet from Web using VBA with exact data format

我已經嘗試了下面的代碼將csv文件導入到Excel工作表(Courtesty: http ://investexcel.net/download-finviz-data/),並且工作正常。 導入數據后,數據類型不正確。 請看截圖。

在此處輸入圖片說明

導入excel后,第二列中刪除了零前綴。 是否有QueryTables.Add(Connection:=“ URL;” ...的任何屬性,例如'.TextFileColumnDataTypes'?

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

這工作得很好:

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:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM