VBA中的简单循环无法正常工作

时间:2016-06-25 22:07:49

标签: vba excel-vba excel

这是我第一次在VBA中编写任何代码 - 我正在尝试编写一个读取文件的短宏,并将位和片段分成西列或东列。

所有这些都可能是错误的,或者它可能只是简单的东西,但目前它甚至不会识别我的循环。非常感谢任何帮助。

    Private Sub seperateTextFile()
    Dim file As String
    Dim text As String
    Dim textLine As String

    Dim west As Boolean
    west = True

    file = ".alltxt"

    Open file For Input As #1

    Do Until EOF(1)
        Line Input #1, textLine
        text = textLine
        If InStr(text, "HMW") <> 0 Then
            west = True
        If InStr(text, "other") <> 0 Then
            west = False
        If west = True Then
            Sheets("Sheet2").Range("West").End(x1Up) = text
        If west = False Then
            Sheets("Sheet2").Range("East").End(x1Up) = text
    Loop

    Close #1

    End Sub

1 个答案:

答案 0 :(得分:1)

我认为你错过了{ifer} elesif。你需要一个End if

Dim file As String
Dim text As String
Dim textLine As String

Dim west As Boolean
west = True

file = "c:\temp\a.alltxt"

Open file For Input As #1

Do Until EOF(1)
    Line Input #1, textLine
    text = textLine
    If InStr(text, "HMW") <> 0 Then
        west = True
    ElseIf InStr(text, "other") <> 0 Then
        west = False
    ElseIf west = True Then
        'Sheets("Sheet2").Range("West").End(x1Up) = text
    ElseIf west = False Then
        'Sheets("Sheet2").Range("East").End(x1Up) = text
    End If
Loop

Close #1

我的file = ".alltxt"对我来说需要有一个实际路径和名称,例如file = "c:\temp\a.alltxt"