2016-05-23 89 views
1

下面是從文本文件中複製數據並將其粘貼到Excel中的代碼。我已將文字分割爲vbNewline,但我還需要按空格分割。將文本文件中的數據複製到Excel中

有沒有其他方法可以通過空間分割數據,以及如何通過分割數據vbNewLine空間?

On Error Resume Next 

Dim objFSO, strTextFile, strData, strLine, arrLines 

Const ForReading = 1 

path = InputBox("Enter the path :","Select Your Path !","Type your path here") 

'name of the text file 
strTextFile = path 

'Create a File System Object 
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject") 

'Open the text file - strData now contains the whole file 
strData = objFSO.OpenTextFile(strTextFile, ForReading).ReadAll 

'typesplit=inputbox("Enter the type ","Type to split(VbnewLine (or) <Space>)","vbnewline/space") 

'Split the text file into lines 
arrLines = Split(strData, vbNewLine) 

Set objExcel = CreateObject("Excel.Application") 
objExcel.Visible = True 
objExcel.Workbooks.Add 

intRow = 2 
k = 0 

align = InputBox("Enter the type of alignment...(default/horizontal/vertical)", _ 
     "Press h (or) v (or) d") 

If (align = "v") Then 
    rowlimit = InputBox("Enter the row limit") 
    For i=1 To 10 Step 1 
    For j=1 To rowlimit Step 1 
     objExcel.Cells(j, i).Value = arrLines(k) 
     k = k+1 
    Next 
    Next 
End If 

If (align = "h") Then 
    collimit = InputBox("Enter the col limit") 
    For i=1 To 10 Step 1 
    For j=1 To collimit Step 1 
     objExcel.Cells(i, j).Value = arrLines(k) 
     k = k+1 
    Next 
    Next 
End If 

MsgBox("Conversion Finished !!") 

Set objFSO = Nothing 
+0

謝謝Ansgar Wiechers –

+1

爲什麼用戶必須輸入行限制和列限制等內容?難道不能從數據中推斷出來嗎?您可以考慮在文本文件中用逗號替換空格並將其保存爲csv文件 - Excel知道如何打開(併爲其他對齊運行轉置)。另外,請看看文本到列如何在Excel中工作。 –

+0

您也可以嘗試自動化[文本到列](https://msdn.microsoft.com/en-us/library/office/ff193593.aspx)功能 –

回答

3

VBScript不允許您在一個步驟中通過多個分隔符分割字符串。您需要通過第一個分隔符分割它,然後遍歷結果數組,然後通過第二個分隔符分割子串,依此類推。

For Each line In Split(strData, vbNewLine) 
    For Each word In Split(line, " ") 
    'do something with each word 
    Next 
Next 

如果你希望把所有的話到一個單一的陣列之後的處理你把它們放入一個動態調整大小的數組:

ReDim words(-1) 'define empty resizable array 
For Each line In Split(strData, vbNewLine) 
    For Each word In Split(line, " ") 
    ReDim Preserve words(UBound(words)+1) 
    words(UBound(words) = word 
    Next 
Next 

另外,您可以使用一個ArrayList

Set words = CreateObject("System.Collections.ArrayList") 
For Each line In Split(strData, vbNewLine) 
    For Each word In Split(line, " ") 
    words.Add word 
    Next 
Next 

請注意,動態VBScript數組對大量數據執行效果不佳,因爲每次調整數組大小時,解釋器都會創建一個新數組,從而將所有數據從exi sting數組,然後將新數組分配給變量。

在另一方面,實例化對象ArrayList裝置大量的開銷,所以如VBScript內置陣列對於少量數據的它不執行爲好。

+0

再次感謝Ansgar Wiechers .. –

+0

@sebastinsaba不客氣。不過,約翰科爾曼提出了一些有效的觀點。你的問題不太清楚你需要什麼「手動」行/列限制。根據您實際想要達到的目標,可能有更好的方法來處理您的數據。 –

+0

如果我使用每個循環而不是循環,將相應的值的單元格可以正確插入像(1,1)(1,2)(1,3)(2,1)(2,2)(2 ,3)反之亦然。 –

相關問題