如何使用VBA将特定数据从记事本导入Excel工作表

时间:2017-01-25 08:05:19

标签: excel vba

首先,我将展示我的记事本的外观。请参阅附图。然后我将解释我在寻找什么。

enter image description here

由此我想将“Cutter PA Value”,Cutter BR Value& Cutter Radius Value导入到excel工作表的单独列中。我的Excel工作表将列名为Cutter PA,Cutter Radius,Cutter BR。我想要记事本值将在每个相应列内输入。 请指导我如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

这些方面的东西应该有效。我还没有测试你的文本文件,但你应该可以从中解决它......

Sub ImportText()

Dim LineString As String
Dim sSourceFile As String
Dim r As Long
Dim fLen As Long
Dim fn As Integer
Dim CutterPA, CutterBR, CutterRad As Double

'Text file and path
sSourceFile = "C:\filtest.txt"

'sSourceFile doesn't exist
If Len(Dir(sSourceFile)) = 0 Then Exit Sub

'Gets a free file number from the operating system
fn = FreeFile

'Opens the file for input
Open sSourceFile For Input As #fn
fLen = LOF(fn)
r = 2
While Not EOF(fn)
   Line Input #fn, LineString

    If InStr(LineString, "(Cutter PA)") > 0 Then
        CutterPA = Val(Split(LineString, "=")(1))
    End If

    If InStr(LineString, "(Cutter BR)") > 0 Then
        CutterBR = Val(Split(LineString, "=")(1))
    End If

    If InStr(LineString, "(Cutter Radius)") > 0 Then
        CutterRad = Val(Split(LineString, "=")(1))
    End If

    'Write values if new item
    If InStr(LineString, "(***********") > 0 Then
        With ActiveSheet
            .Cells(r, 1).Value = CutterPA
            .Cells(r, 2).Value = CutterBR
            .Cells(r, 3).Value = CutterRad
        End With

        r = r + 1
    End If


Wend

'Closes the text file
Close #fn

End Sub