将数据从文本文件复制到Excel

时间:2016-05-23 10:28:41

标签: vbscript

以下是从文本文件中复制数据并将其粘贴到Excel的代码。我已将文本拆分为vbNewline,但我还需要按空格拆分。

是否有其他方法可以按空格分割数据,以及如何通过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

1 个答案:

答案 0 :(得分: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数组在处理大量数据时效果不佳,因为每次调整数组大小时,解释器都会创建一个新数组,从现有数组中复制所有数据,然后将新数组分配给变量。

另一方面,实例化ArrayList对象意味着很多开销,因此它不会像少量数据的VBScript内置数组那样执行。