2016-06-10 40 views
0

目前我正在写一个VBS来从excel报表中获取值。 试图使用DO直到循环来获取所有矩阵数据。 但是,我的脚本只能得到一个循环的结果(只有一行行X COL),但不能进入下一个循环。 可以请指教我错过任何价值让脚本在下一个工作?VBS从excel矩阵表中获取值到txt

非常感谢。

Set Args = WScript.Arguments 
Set fso = CreateObject("Scripting.FileSystemObject") 

Const ForReading = 1 
Const ForWriting = 2 
Const ForAppending = 8 

WScript.echo "cYear," & "cMonth," & "cEntity," & "cAccount,"& "cAmount" 

cFile = "C:\XXX.xlsx" 


Set objExcel = CreateObject("Excel.Application") 
Set objWorkbook = objExcel.Workbooks.Open(cFile) 
Set objFile = fso.GetFile(cFile) 
cFilename = fso.GetFileName(objFile) 

     intRow = 21 
     intCol = 8 

     'Read xlsx data 



      Do Until objExcel.Cells(13, intCol).Value = "" 

       Do Until objExcel.Cells(intRow, 2).Value = "" 
       cYear = objExcel.Cells(2, 2) 
       cMonth = objExcel.Cells(3, 2) 
       cEntity = objExcel.Cells (13, intCol) 
       cAccount = objExcel.Cells(intRow, 2)    
       cAmount = objExcel.Cells(intRow, intCol) 

         WScript.echo cYear &","& cMonth&"," & cEntity&"," & cAccount&"," & cAmount 

    exit do 

     intRow= intRow + 1 

     Loop 

     intCol = intCol + 1 

     loop 

回答

0

随着Dinesh迭代,Exit do绝对是导致您的代码仅产生1行数据的罪魁祸首。

cFile = "C:\XXX.xlsx" 
Set fso = CreateObject("Scripting.FileSystemObject") 
Set objExcel = CreateObject("Excel.Application") 
Set objWorkbook = objExcel.Workbooks.Open(cFile) 
Set objFile = fso.GetFile(cFile) 
cFilename = fso.GetFileName(objFile) 
intRow = 21 
intCol = 8 
'Read xlsx data 
Do Until objExcel.Cells(13, intCol).Value = "" 
    Do Until objExcel.Cells(intRow, 2).Value = "" 
     cYear = objExcel.Cells(2, 2) 
     cMonth = objExcel.Cells(3, 2) 
     cEntity = objExcel.Cells (13, intCol) 
     cAccount = objExcel.Cells(intRow, 2) 
     cAmount = objExcel.Cells(intRow, intCol) 
     WScript.echo cYear &","& cMonth&"," & cEntity&"," & cAccount&"," & cAmount 
     'Will cause the do to terminate after the first row value. 
     'exit do 
     intRow= intRow + 1 
    Loop 
    intCol = intCol + 1 
Loop 

所以我做了我自己的测试,这是输出。使用一个微小的宏来填充电子表格100行x 20列。

Cell B Row 2,Cell B Row 3,Cell H Row 13,Cell B Row 21,Cell H Row 21 
Cell B Row 2,Cell B Row 3,Cell H Row 13,Cell B Row 22,Cell H Row 22 
Cell B Row 2,Cell B Row 3,Cell H Row 13,Cell B Row 23,Cell H Row 23 
Cell B Row 2,Cell B Row 3,Cell H Row 13,Cell B Row 24,Cell H Row 24 
+0

仍然一样,试图删除“exit do”。但脚本仍然只循环一个“row x col”,无法循环全表矩阵 –

+0

您能否以CSV格式提供电子表格的虚拟样本?另一个想法是考虑添加一些W脚本回声,并从命令行运行它,以确切了解哪些数据正在处理,并查看是否存在重复值,您可能在脚本中发现一个小错误,但没有看到示例 数据很难告诉你什么是错 –

+0

@KennethChiu我跑了一个简单的测试 - 见上文。这有助于了解数据来自哪里? –

1

通过删除从您的代码 '退出做' 线。 我想它是有效的。但是,请粘贴您的Excel样本,以便我们更好地了解问题

+0

你为什么要遍历列和行?如果你的数据是5列10行,你会得到50条记录。它是否正确? – 2016-06-10 23:00:34

+0

谢谢,试过。但似乎返回相同的结果。 –

+0

如上所示上传链接的链接。谢谢 –