VBscript用于将数据从.txt复制并粘贴到.xlsx

时间:2017-11-02 18:06:46

标签: excel vbscript

想要创建一个脚本,用于将最后8行从txt文件复制到Excel文件的单元格A,3中。这是我到目前为止所放在一起的东西,它不起作用。基本上从制表符分隔复制到Excel模板文件。请帮忙,因为到目前为止我只在VB中编写了非常基本的脚本。

到目前为止,我正在与之合作....

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\test.txt", ForReading)
for i = Last 8 lines
objTextFile.ReadLine
Next
strLine = objTextFile.ReadLine
Wscript.Echo strLine
objTextFile.Close



Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\NBP ESP-152 REV F TEMPLATE.xlsx")

objExcel.Application.Visible = True
objExcel.Workbooks.Add = i
objExcel.Cells(a, 3).Value = strLine

以下来自Aedvald的脚本一直运行到它应该粘贴到工作簿的位置:

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")

' get number of lines
Set objTextFile = objFSO.OpenTextFile("c:\test.txt", ForReading)
objTextFile.ReadAll
lineCount = objTextFile.Line
objTextFile.Close


Set objTextFile2 = objFSO.OpenTextFile("c:\test.txt", ForReading)

' skip all lines except 8 last
i = 0
while i < lineCount-8
 objTextFile2.ReadLine
 i = i+1
wend

' prepare excel
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("c:\NBP ESP-152 REV F 
TEMPLATE.xlsx")
objExcel.Application.Visible = True

j = 1
' read last 8 lines
Do Until objTextFile2.AtEndOfStream
  ' read line
  line = objTextFile2.ReadLine
  ' write to console
  ' WScript.Echo line (for testing)
  ' and into workbook
  objExcel.Cells(1, j).Value = strLine
  j=j+1
Loop

1 个答案:

答案 0 :(得分:2)

这就是我做的工作:

我打开test.txt并遍历所有行以计算它们。然后我再次打开test.txt并循环直到只剩下8行。然后我将其余8行循环,同时将它们添加到Excel-Workbook第一个工作表的单元格中。

更新:要向Excel工作表添加文本,必须使用工作表的cells-property: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/worksheet-cells-property-excel

====

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")

' get number of lines
Set objTextFile = objFSO.OpenTextFile("C:\test.txt", ForReading)
objTextFile.ReadAll
lineCount = objTextFile.Line
objTextFile.Close


Set objTextFile2 = objFSO.OpenTextFile("C:\test.txt", ForReading)

' skip all lines except 8 last
i = 0
while i < lineCount-8
  objTextFile2.ReadLine
  i = i+1
wend

' prepare excel
Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Visible = True
Set objWorkbook = objExcel.Workbooks.Open("C:\NBP ESP-152 REV F TEMPLATE.xlsx")
Set objWorksheet = objWorkbook.Worksheets(1)

j = 1
' read last 8 lines
Do Until objTextFile2.AtEndOfStream
  ' read line
  line = objTextFile2.ReadLine
  ' write to console
  ' WScript.Echo line ' (for testing)
  ' and into workbook
  objWorksheet.Cells(1, j).Value =  line
  j=j+1
Loop