如何在Excel VBA中获取具有不同长度的特定行

时间:2017-11-21 20:13:31

标签: excel excel-vba vba

大家好,我有下面的文本文件,我保存了myfile.txt;

!File starts 
Some texts here

version.number = 12345

Some texts here
!File ends 

我使用下面显示的代码获取版本号12345,但有时版本号可能是5位或更多。作为一个例子,我如何用我的代码获得6位数123456。

Dim myFile As String
Dim text As String
Dim textline As String
Dim VersionInfo As Integer

Sub DetectModelVersion()

myFile = "C:\test\myfile.txt"

Open myFile For Input As #1

Do Until EOF(1)
    Line Input #1, textline
    text = text & textline
Loop

Close #1

VersionInfo = InStr(text, "version.number")

ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = Mid(text, VersionInfo + 17, 6)

End Sub

1 个答案:

答案 0 :(得分:1)

刚刚测试了以下代码并且它有效。

Option Explicit

Dim myFile As String
Dim text As String
Dim textline As String

Sub DetectModelVersion()

    myFile = "H:\myfile.txt"

    Open myFile For Input As #1

    Do Until EOF(1)
        Line Input #1, textline
        If InStr(textline, "version.number") Then
            text = Trim(Mid(textline, InStr(textline, "=") + 1, 255))
            Exit Do
        End If
    Loop

    Close #1

    ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = text

End Sub