VBA代码将.txt文件中的特定数据提取到Excel

时间:2017-08-07 11:54:06

标签: excel vba excel-vba

我有一个.txt文件,其中包含需要提取的特定数据并放入Excel中的相应列中。下面显示了我到目前为止的代码,但在运行时,它只提取第一组数据,但不会移动到下一个文本块。

在我需要的Excel文件中:

Description (company Name) | Speed (eg 1M) | Service Num. (7-digit number after the speed). 

以下是.txt文件中的示例数据:

#
interface GigabitEthernet5/
vlan-type aser 7878
description ABC_COMPANY_1M_1254589_4444243
ip binding vpn-instance internet_vpn
ip address 158.214.125.215 
#
interface GigabitEthernet5/0
vlan-type frin 2255
description XYZ_COMPANY_6M_1458963_444
ip binding vpn-instance internet_vpn
ip address 148.214.25.214
#

所需的所有数据都来自interface GigabitEthernet行,例如

Description: ABC_COMPANY | Speed: 1M | Service Num: 1254589 

在这些块之前和之后还有大量数据不需要提取。

下面的代码正确提取,但不会移动到下一个所需数据块:

Private Sub CommandButton1_Click()
Dim myFile As String, find1 As String, i As Integer, und As String, speed2 As Integer,_
text As String, Desc As String, r As Long, dashpos As Long, m As Long, textline As String,_
posLat As Integer, posLong As Integer, strLeft As String, strFind As String,_
strRight As String, strMid As String, speed As String

myFile = "C:\dump2.txt"

Open myFile For Input As #1

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

Close #1

Desc = InStr(text, "interface GigabitEthernet")
speed = InStr(text, "M_")

Range("A1").Value = "Description"
Range("B1").Value = "Speed"
Range("c1").Value = "Service Num"

Range("A2").Value = Mid(text, Desc + 68, 30)
Range("b2").Value = Mid(text, speed + -3, 4)

und = Mid(text, speed + -3, 4)

speed2 = InStr(1, und, "_")

Dim finalString As String
finalString = Right(und, Len(und) - speed2 + 0)
Range("b2").Value = finalString

Desc = InStr(text, "interface GigabitEthernet")
speed = InStr(text, "M_")
Range("C2").Value = Mid(text, speed + 2, 6)
End Sub

0 个答案:

没有答案