2017-07-18 84 views
0

我試圖自動將數據導入到我在Excel中創建的工具中。我們的想法是將.csv文件中的數據直接讀入數組中,或者將數據作爲字符串讀取,然後使用空格「」和逗號「,」作爲分隔符,然後是數組進行解析。這一步我已經得到了:使用VBA將.csv字符串讀取到多維數組中

Public Sub ImportData() 
    Dim myData as String, strData() as String 
    Dim thisFile as String 

    thisFile = ActiveWorkbook.Path & "\" & "s.csv" 
    Open thisFile For Binary As #1 
    myData = Space$(LOF(1)) 
    Get #1, , myData 
    Close #1 
End Sub 

這讓我到哪裏「的myData」是現在逗號和空格(逗號劃定了一個新的列,空間界定爲一個新行)分隔的數據串。

如何繼續將其重建爲多維(2D)數組,以便它可以打印到正在處理的工作表上,或從內存中直接引用?還是有更簡單的方法?

+0

斯普利特((那些真的不換行符 - 這將是一個CSV文件奇數格式)給你的「線陣列」。然後用逗號分隔每一行(假設您沒有可能包含逗號的字段值?)以獲取每行中的單個值。 –

+0

你確定你想要一個動態數組嗎?換句話說,你是否想要兩個以上的「列」數據?這對於CSV工作來說似乎很不尋常,除非您只是構建標題行和列。也許你想要一個具有兩列數據的二維數組,但是是一個動態行?如果你發佈了你擁有的字符串以及你希望數組包含的內容(例如strdata(0,0)= xx strdata(0,1)= xxxxx – PGCodeRider

+0

),那麼在這裏檢查一個關於導入文本(csv)文件.... https://stackoverflow.com/questions/10434335/text-file-in-vba-open-find-replace-saveas-close-file#10434907 – jsotola

回答

0

這是空格)由@Tim建議實施

Option Explicit 

Public Sub OpenFile() 
    Dim rawData As String, lineArr As Variant, cellArr As Variant 
    Dim ubR As Long, ubC As Long, r As Long, c As Long 

    Open ActiveWorkbook.Path & "\" & "s.csv" For Binary As #1 
    rawData = Space$(LOF(1)) 
    Get #1, , rawData 
    Close #1 

    If Len(rawData) > 0 Then 

     'If spaces are delimiters for lines change vbCrLf to " " 
     lineArr = Split(Trim$(rawData), vbCrLf) 

     ubR = UBound(lineArr) + 1 
     ubC = UBound(Split(lineArr(0), ",")) + 1 
     ReDim arr(1 To ubR, 1 To ubC) 

     For r = 1 To ubR 
      If Len(lineArr(r - 1)) > 0 Then 
       cellArr = Split(lineArr(r - 1), ",") 
       For c = 1 To ubC 
        arr(r, c) = cellArr(c - 1) 
       Next 
      End If 
     Next 
     ActiveSheet.Range(Cells(1), Cells(ubR, ubC)) = arr 'Place array on the sheet 
    End If 
End Sub