2013-03-06 137 views
0
Set objReadFile = objFSO.OpenTextFile(objFile.Path, ForReading) 
    strAll = Split(objReadFile.ReadAll, vbCrLf, -1, vbTextCompare) 'Gets each line from file 
    i = LBound(strAll) 
    Do While i < UBound(strAll) 
     If (InStr(1, strAll(i), "DAU SNo.-C0", vbTextCompare) > 0) Then 
      i = i + 4 'Skip 4 lines to get to first SN 
      Do Until InStr(1, strAll(i), "+", vbTextCompare) > 0 'Loop until line includes "+" 
      strSNO = Split(strAll(i), "|", -1, vbTextCompare) 
      'put strSNO into next cell in column A 
      **objSheet.Cells.Offset(1,0).Value = Trim(strSNO(1))** 
      i = i + 1 
      Loop 
     End If 
    i = i + 1 
    Loop 

此代碼成功分割文本文件,並將我想要的兩個值放入strSNO(1)和strSNO(2)中。我想將它們寫入列A行2和列B行2中,然後在循環的下一次迭代中將下一個值放入行3中。我嘗試了偏移方法,它給出了錯誤。我發現的所有幫助都是針對VBA的。任何人都可以告訴我該放置代碼以粗體顯示的位置嗎?如何使用VBscript在Excel中的單元格中輸入值

編輯:

解決it.This是我做過什麼:

strAll = Split(objReadFile.ReadAll, vbCrLf, -1, vbTextCompare) 'Gets each line from file 
    i = LBound(strAll) 
    c=2 
    Do While i < UBound(strAll) 
     If (InStr(1, strAll(i), "DAU SNo.-C0", vbTextCompare) > 0) Then 
      i = i + 4 'Skip 4 lines to get to first SN 
      Do Until InStr(1, strAll(i), "+", vbTextCompare) > 0 'Loop until line includes "+" 
      strSNO = Split(strAll(i), "|", -1, vbTextCompare) 
      i = i + 1 
      objSheet.Cells(c,1).Offset(1,0).Value = Trim(strSNO(1)) 
      objSheet.Cells(c,2).Offset(1,0).Value = Trim(strSNO(2)) 
      c=c+1 
      Loop 
     End If 
    i = i + 1 
    Loop 
+0

注意'objSheet.Cells(C,1).Offset(1,0 )'與'objSheet.Cells(c + 1,1)'相同。 – 2013-03-08 19:09:44

回答

0

更換

objSheet.Cells.Offset(1,0).Value = Trim(strSNO(1)) 

objSheet.Cells(i,1).Value = Trim(strSNO(1)) 
objSheet.Cells(i,2).Value = Trim(strSNO(2)) 

編輯:你確定你想要strSNO的字段1和2嗎?的VBScript陣列0爲基礎的,所以第一個索引是0,而不是1

要查找錯誤添加一些調試代碼:

On Error Resume Next 
objSheet.Cells(i,1).Value = Trim(strSNO(1)) 
If Err Then 
    WScript.Echo i & ": " & strAll(i) 
    WScript.Echo "strSNO(1) = " & strSNO(1) 
    WScript.Echo "strSNO(1) is of type " & TypeName(strSNO(1)) 
End If 
Err.Clear 
objSheet.Cells(i,2).Value = Trim(strSNO(2)) 
If Err Then 
    WScript.Echo i & ": " & strAll(i) 
    WScript.Echo "strSNO(2) = " & strSNO(2) 
    WScript.Echo "strSNO(2) is of type " & TypeName(strSNO(2)) 
End If 
On Error Goto 0 

如果問題被證明是該strAll(i)不包含一個|一些i,所以Split()產生只有一個元素的數組,你可以解決,通過這樣的:

strSNO = Split(strAll(i) & "|", "|", -1, vbTextCompare) 
+0

我試過了。它給了我一個指向該行的錯誤:下標超出範圍:'number:1'但是使用Msgbox strSNO(1)或Msgbox strSNO(2)完美地工作,在每次迭代時在窗口中顯示我想要的值。 – SamSong 2013-03-06 21:51:01

+0

我驗證了strSNO(1)和strSNO(2)包含我想要使用Msgbox的值。這是正確的,並增加到文本文件中的下一行,證明解析是正確的。 – SamSong 2013-03-07 14:12:31

相關問題