VBA编码从.txt文件中提取数据

时间:2017-01-11 07:43:40

标签: excel-vba vba excel

我尝试使用以下编码从.txt文件中提取数据。但是,我不知道如何保持负值,因为当我运行编码时,负号将丢失。请帮忙。

enter image description here

Private Sub CommandButton1_Click()

Dim myFile As String, text As String, textline As String, Point1 As Integer, LastRow As Long, Filename As String, x As Variant

'Open File Location
myFile = Application.GetOpenFilename()

'Read the data file
Open myFile For Input As #1

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

Loop

Close #1 'Close data file

'Defined starting point
 Point1 = InStr(text, "Coord. Z")

'Adding new line
LastRow = Sheet2.Range("A" & Rows.Count).End(xlUp).Row + 1

'Get Module S/N from filename
strFilePath = myFile
Filename = Replace(Dir([strFilePath]), ".txt", "")

'Location of the data
Sheet2.Range("A" & LastRow).Value = Filename
Sheet2.Range("B" & LastRow).Value = Mid(text, Point1 + 21, 8)
Sheet2.Range("C" & LastRow).Value = Mid(text, Point1 + 36, 8)
Sheet2.Range("D" & LastRow).Value = Mid(text, Point1 + 54, 8)
Sheet2.Range("E" & LastRow).Value = Mid(text, Point1 + 70, 8)
Sheet2.Range("F" & LastRow).Value = Mid(text, Point1 + 84, 8)
Sheet2.Range("G" & LastRow).Value = Mid(text, Point1 + 103, 8)

`End Sub

1 个答案:

答案 0 :(得分:0)

假设文本文件只包含一行Coord。 Z和值由空格分隔,您也可以扫描该行并使用以下代码拆分为数组;

Dim vTmp as variant
Dim i as long, j as long

Do Until EOF(1)
Line Input #1, textline
If InStr(text, "Coord. Z") then vTmp = split(textline, " ")
Loop

此代码生成一个数组vTmp,其中包含已连接的字符(如果存在双空格,则为空条目)

接下来遍历生成的数组并将值转储到工作表中。

j = 1 'Start column

'Loop through array
For i = LBound(vTmp) to UBound(vTmp)
    If vTmp(i) <> "" 'If entry is not empty
        Sheet2.Cells(LastRow, j).value = vTmp(i) 'Dump entry
        j = j + 1 'Next column
    End if
Next i