如何使用VBscript在Excel中的单元格中输入值
问题描述:
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
答
更换
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)
注意'objSheet.Cells(C,1).Offset(1,0 )'与'objSheet.Cells(c + 1,1)'相同。 – 2013-03-08 19:09:44