excel - 使用 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,当我按下调试时,它会使用 .Refresh BackgroundQuery 突出显示该行
我没有把所有东西都放在这里,比如尺寸标注等,因为我必须用手机才能访问这个网站,所以我再次用手机编写所有代码。
编辑:我添加了更多行,当我按下调试时,问题突出显示了 Refresh Background Query 行。我实际上是试图通过调整我的问题来实现这一点:
解决方案
使用此函数从文本文件中读取特定行
' 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)
推荐阅读
- javascript - 如何将数据传递给嵌套的子组件vue js?
- jhipster - jhipster update --force 对现有项目
- python - 为空参数设置默认值 (Python)
- mysql - 如何读取数据文件并将数据插入mysql数据库
- python - 为什么 git clone 无法在 Linux Mint 上统计文件?
- android - 是否在操作系统重启后调用 onActivityResult() 之前重新创建了活动的视图?
- python - 日期时间:ValueError:只能比较标签相同的系列对象 - Python
- android - 我应该在 AndroidStudio 中使用 .gitignore Application/build/ 文件夹吗?
- javascript - 输入时如何禁用热键?
- angular - 作为从共享模块导入的子路由到组件的角度路由