我用excel里面的vba,导入txt文件。txt文件是其他系统自动生成的,用tab做分隔符。
现在可能被导入的文件有两种,文件名上面没有什么区分,在数据内容上一种是28个column,一种是30个column。所以,想请教能否在With ActiveSheet.QueryTables.Add(Connection:= _...语句前先做column判断,然后决定用哪一个.TextFileColumnDataTypes = Array(9, 2, 2, 9, 9, 9, 2, 2, 2, 2, 2, 9, 9, 9, 1, 9, 2, 2, 2, 2, 1, 1, 9, 1, 1, 9, 1, 9, 9, 9)语句。
有没有专家能给我建议啊?
------解决方案--------------------------------------------------------
导入到一个临时的工作表中来判断或者读取文本文件第一列,然后用splict分割后来判断。
------解决方案--------------------------------------------------------
先读取第一行,然后用Split函数分割就可以得出列数。
下面是一段读取第一行的脚本:
Const ForReading = 1
Set objFSO = CreateObject( "Scripting.FileSystemObject ")
Set objTextFile = objFSO.OpenTextFile( "你的文本文件路径和名称 ", ForReading)
strLine = objTextFile.ReadLine Wscript.Echo strLine
objTextFile.Close
然后:
ww=split(strline,vbtab)
ubound(ww)+1就是你需要的列数
------解决方案--------------------------------------------------------
' Dim str
' Open "C:\my document\新規テキスト ドキュメント.txt " For Input As #1
' Line Input #1, str
' Dim arr() As String
' arr = Split(str, vbTab)
' MsgBox UBound(arr)
' Close #1