[英]VBA loop with InStr for a .txt file
我在嘗試從.txt file
導入信息時遇到問題。 我在文件中有以下數據:
EMPRESA : TRANSENER S.A.
---- NODO -------------------- INYECCION
Descripción VNom (MW)
ALICURA 500 2 500 251.8
---- LINEAS ------------------ PARTIC CHPOTik REMUNERACION
Descripción VNom (%) ($/H) MENSUAL ($)
ACABRAL-R.OESTE 500.0 500 0.15 5.24 3775.62
ALMAFUE.-ACABRAL 500.0 500 0.15 1.85 1335.12
------------------------------
---- NODO -------------------- INYECCION
Descripción VNom (MW)
SANTO TOME 500 2 500 101.2
---- LINEAS ------------------ PARTIC CHPOTik REMUNERACION
Descripción VNom (%) ($/H) MENSUAL ($)
ALMAFUE.-EMBALSE-500-1 500 0.15 0.25 179.54
CHACO500-RESISTEN 500.0 500 0.10 0.17 124.02
------------------------------
---- NODO -------------------- INYECCION
Descripción VNom (MW)
ALMAFUERTE 1.0 3 1 -9.5
---- LINEAS ------------------ PARTIC CHPOTik REMUNERACION
Descripción VNom (%) ($/H) MENSUAL ($)
ALMAFUE.-EMBALSE-500-1 500 0.15 0.25 179.54
CHACO500-RESISTEN 500.0 500 0.10 0.17 124.02
我想提取任何總線(NODO)的信息:
Name Vnom ( MW )
ALICURA 500 2 500 251.8
SANTO TOME 500 2 500 101.2
ALMAFUERTE 1.0 3 1 -9.5
我編寫此代碼,但僅適用於第一個代碼:
Private Sub BarrasIny_Click()
Dim myFile As String
Dim text As String
Dim quote As String
Dim textline As String
myFile = "C:\Users\tvelis\Desktop\CFCT_por_barra2.txt"
Open myFile For Input As #1
Do Until EOF(1)
Line Input #1, textline
text = text & textline
Loop
Close #1
quote = InStr(text, "---- NODO")
Range("A1").Value = "Barra"
Range("B1").Value = "Tension"
Range("c1").Value = "MW"
Range("A2").Value = Mid(text, quote + 103, 30)
Range("B2").Value = Mid(text, quote + 136, 3)
Range("C2").Value = Mid(text, quote + 145, 5)
End Sub
我該如何做一個循環並從任何總線(NODO)中提取信息?
我已經嘗試了以下內容,但我相信它與您要實現的目標非常接近,使用計數器來檢查NODO並獲取下面兩行的值,然后獲取文本行的值並將它們拆分為一個數組,然后遍歷數組以將值放入Sheet中:
Private Sub BarrasIny_Click()
Dim myFile As String
Dim text As String
Dim quote As String
Dim textline As String
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
Dim arr(0) As Variant
myFile = "C:\Users\tvelis\Desktop\CFCT_por_barra2.txt"
counter = 0
Open myFile For Input As #1
Do Until EOF(1)
Line Input #1, textline
counter = counter + 1
If InStr(textline, "--- NODO") > 0 Then counter = 0
If counter = 2 Then
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1
b = 2
arr(0) = Split(textline, " ")
For c = LBound(arr(0)) To UBound(arr(0))
If arr(0)(c) <> "" Then
If Not IsNumeric(arr(0)(c)) Then
ws.Cells(LastRow, 1).Value = Trim(ws.Cells(LastRow, 1).Value & " " & arr(0)(c))
y = LastRow
Else
ws.Cells(y, b).Value = arr(0)(c)
b = b + 1
End If
x = x + 1
End If
Next c
End If
Loop
Close #1
ws.Range("A1").Value = "Barra"
ws.Range("B1").Value = "Tension"
ws.Range("C1").Value = "MW"
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.