简体   繁体   English

使用VBA将特定行从文本文件导入Excel电子表格

[英]Import specific lines from text file into Excel spreadsheet using VBA

I'm trying to get a macro setup that will import specific lines from a text file into a Excel spreadsheet. 我正在尝试获取一个宏设置,该设置会将文本文件中的特定行导入到Excel电子表格中。 I am currently using the instr function to locate a specific word then read how many letters over I need to import data into the cells. 我目前正在使用instr函数来查找特定单词,然后读取将数据导入单元格所需的字母数。

The reason I am doing it this way is due to the file being over 3500 lines and is not delimited or comma separated in any sense. 我这样做的原因是由于文件超过3500行,并且在任何意义上都没有定界或逗号分隔。 Some of the data is the same as well which I run into problems with the above tactic. 一些数据也相同,而我在上述策略中遇到了问题。

What I need help with is how to import only like 20 specific lines into the spreadsheet(multiple sheets will be used, but can reuse this code), while using a technique like I mentioned earlier so I can decide where its reading from. 我需要帮助的是如何仅将20条特定的行导入到电子表格中(将使用多张工作表,但可以重复使用此代码),同时使用前面提到的技术,以便确定从何处读取。

Thanks! 谢谢!

This is what I use constantly. 这就是我经常使用的。 Just replace the file location with your text file and this little blip will read it line by line. 只需将文件位置替换为文本文件,这个小提示将逐行读取它。 Then you can throw logic against a single line and decide what to do with it. 然后,您可以将逻辑放在一行上并决定如何处理。 Its a good solution when your dealing with data that regex statements can't handle accurately. 当您处理正则表达式语句的数据无法正确处理时,这是一个很好的解决方案。

Sub LoadSettings()
Dim fso As Scripting.FileSystemObject
Dim F As File
Dim F2 As TextStream
Dim TS As TextStream
Dim lngCount As Long


Set fso = New Scripting.FileSystemObject

fileloc = "Whereyourtextfileislocated"
Set F = fso.GetFile(fileloc)


Set TS = F.OpenAsTextStream(1, -2)

S = ""
Do

RptText = TS.ReadLine

if rpttext = whatever criteria, or even if instr(rpttext,"whateveryouwant")     >0 then
    do something with rpttext
end if

Loop

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM