读取一个文本文件,并使用正则expression式应用于结果string

我会读一次文本文件的内容,并应用正则expression式的结果string。 我一直无法弄清楚如何阅读文本文件。

有一个替代我一直在尝试,但它不能正常工作

Set oFS = oFSO.OpenTextFile(sFilename) num = 15 mynum = 1 Do Until oFS.AtEndOfStream 'Cells(num, mynum).Value = oFS.ReadLine MyString = oFS.ReadLine If Not oFS.AtEndOfStream Then oFS.SkipLine strStrings = Split(MyString, " ") For intInd = LBound(strStrings) To UBound(strStrings) Cells(num, mynum).Value = strStrings(intInd) mynum = mynum + 1 If mynum Mod 4 = 0 Then num = num + 1 mynum = 1 End If Next End If Loop oFS.Close Set oFSO = Nothing 

我注意到这个问题来自两个来源…一旦我们的函数被拆分的string是可变长度的,一个函数就会失败。 我怎么能修补这个? 其次,我的文件内容中有一些我非常怀疑的非字符也可能导致这个问题。 Myfile在第三行之后有不同的空间。 我能够得到前两行

DNI ROLL TEST ON 896_271209

定向数据testing开始

=> KS 32223.63 Flammas

=> SIP -7.25 Deg

=>右90.57 Deg

=> AZIMUTH 105.46 Deg

=>左73.92度

=> OFFSET -1.15 Deg

这是一个非常有用的代码sniplet我以前用过,将存储在一个string,然后你可以工作(像使用正则expression式)的整个文本文件。

 Dim strFile As String Dim intFile As Long intFile = FreeFile Open "C:\File.txt" For Input As #intFile strFile = Input$(LOF(intFile), #intFile) ' LOF returns Length of File Close #intFile 'Do what you want with strFile 

更新 :其实,这是我发现更安全的方法。 我甚至已经显示如何使用打开的对话框来获取文件名,这是非常方便的:

 Sub test() Dim fileString As String Dim fileName As String ' You can use GetOpenFilename() if you like fileName = Application.GetOpenFilename("Text Files (*.txt,*.txt") fileString = Space(FileLen(fileName)) Open fileName For Binary As #1 Get #1, , fileString Close #1 ' Do what you wish with fileString MsgBox Len(fileString) End Sub 

如果你改变这一行:

 Cells(num, mynum).Value = strStrings(intInd) 

至:

 Cells(num, mynum).Value = "'" & strStrings(intInd) 

它会强制Excel将每行看作文本。 我不认为它喜欢“=>”中的等号,因为在Excel中通常使用等号表示公式。

以下是我在运行该更改时得到的输出:

在这里输入图像说明

这对我来说似乎并不是很有用,但是我不确定这是否给出了您正在寻找的输出 – 您没有提供关于输出结果的详细信息。 这应该有助于摆脱你的“应用程序定义或对象定义的错误”,虽然。

如果你想在文本上运行正则expression式,请解释你正在寻找你的程序,我相信我们其中一个可以帮你写一个正则expression式。

后来我得到了上面的代码工作..

 Set oFS = oFSO.OpenTextFile(sFilename) num = 15 mynum = 1 Do Until oFS.AtEndOfStream 'Cells(num, mynum).Value = oFS.ReadLine MyString = oFS.ReadLine Do While InStr(MyString, " ") MyString = Replace(MyString, " ", " ") Loop strStrings = Split(MyString, " ") If UBound(strStrings) > 0 Then For intInd = LBound(strStrings) To UBound(strStrings) If Not strStrings(intInd) = "=>" Then Cells(num, mynum).Value = strStrings(intInd) mynum = mynum + 1 If mynum Mod 5 = 0 Then num = num + 1 mynum = 1 End If End If Next End If