繁体   English   中英

使用VBA读取文本行的特定部分

[英]Reading a specific part of a text line using VBA

我试图从文本文件中获取第827行以写入单元格。 有很多这样的文件,所以这就是为什么我尝试使用宏的原因。 文本文件如下所示

"Drag Convergence"
"Iterations" "cd"
1     7.74776e-01
2     6.51021e-01
3     5.58885e-01
.....
824     3.57617e-01
825     3.57617e-01

我只想在单元格中写入数字“ 3.57617e-01”。 我可以自己进行单元格排列,但是我没有很好的方法来读取该值,然后将其写入单元格,说(1,1)

我的文件位置是

strFile = "D:\Analiz\Database\NACA63220_" & Mach(k) & Alpha(j) & Letter(i) & ".txt"

我所做的是使用

strPath = "D:\Analiz\Database\"
strExt = ".txt"
strSection = "Lift Convergence"
strValue = "825     "

With shtResult
     .Cells(1,1).Value = strValue
End With

strFile = "D:\Analiz\Database\NACA63220_" & Mach(k) & Alpha(j) & Letter(i) & ".txt"

Set data=shtSource.QueryTables.Add(Connection:TEXT;" & strPath & strFile, Destination:=shtSource.Cells(1, 1))

With data
.TextFileStartRow = 1
.TextFileParseType = xkDelimited
.TextFileVonsecutiveDelimeter = False
.TextFileTabDelimiter = False
.Text FileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True

.Refresh BackgroundQuery:=False
End With

Set fndSection = data.ResultRange.Find(strSection)
Set fndValue = data.ResultRange.Find(strValue, fndSection)
shtResult.Cells(shtResult.Rows.Count, 1).End(xkUp).Offset(1).Value = Replace(findValue, strValue, "")

这给出了运行时错误1004,当我按debug时,它以.Refresh BackgroundQuery突出显示了该行。

我没有将尺寸标注等内容放到这里,因为我必须使用手机访问此站点,因此我将再次用手机编写所有代码。

编辑:我添加了更多的行,当我按调试时,问题突出显示了刷新背景查询行。 我实际上是通过调整我的问题来尝试实现这一点:

将多个文本文件中的数据导入Excel VBA

使用此功能从文本文件读取特定行

    ' read specific line no.
    ' RESULT : searched text (string)
    Function ReadLine(FilePath, LineNumber) As String
    Dim i As Integer, count As Long
    Dim strLine As String
    i = FreeFile
    Open FilePath For Input As #i
    count = 0

    While Not EOF(i)
        Line Input #i, strLine
        count = count + 1
        If count = LineNumber Then
            ReadLine = strLine
            Close #i
            Exit Function
        End If
    Wend

Close i
End Function

您在执行方面还有其他问题吗? 请澄清

第二个代码用于字符串拆分

     Function BreakString(a As String, pos As Integer) As String
     Dim WrdArray() As String
     WrdArray() = Split(a, "     ")
     BreakString = WrdArray(pos)
     End Function

Dim Text, Part1, Part2 As String
Text = "827     3.57617e-01"
Part1 = BreakString(CStr(Text), 0)
Part2 = BreakString(CStr(Text), 1)

我建议您不要在此问题上使用标准的VBA文件处理:VBA文件处理从第一行开始读取文件,然后逐行继续,直到到达您要查找的行。 由于您需要阅读827行,因此您等待827时间太长,无法做出响应。

取而代之的是,我将尝试找到一个可以处理此问题的命令行,例如:

tail -1 <filename> >output.txt (or head -827 <filename> | tail -1 >output.txt)

将此转换为Excel VBA,类似于:

Shell "tail -f <filename> >output.txt" //pseudo-code

然后,使用VBA标准文本处理读取output.txt。

暂无
暂无

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

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