2016-06-10 41 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

如上所示上傳鏈接的鏈接。謝謝 –