VBA:Else without If 错误

7

我试图运行以下代码,但是在第一个子程序中一直出现“Else without If”错误。该代码应该通过一列运行,如果单元格中有url,则打开网页,然后将页面信息保存为文本文件。如果没有url,则只将该文件中的文本保存为文本文件。我无法弄清楚如何更改语法以使其正常工作。

Sub LoopOverB()

Dim myRow As Long

myRow = 10

While Worksheets("Input_Format_A").Cells(myRow, 2).value <> ""
    If InStr(1, Worksheets("Input_Format_A").Cells(myRow, 2).value, "http://", vbTextCompare) Then Call url_Test(Worksheets("Input_Format_A").Cells(myRow, 2).value, "C:\mallet\test\" & Worksheets("Input_Format_A").Cells(myRow, 1).value & ".txt")
        myRow = myRow + 1
    Else
        Open "C:\mallet\test\" & Worksheets("Input_Format_A").Cells(myRow, 1) & ".txt" For Append As #1
        Print #1, Worksheets("Input_Format_A").Cells(myRow, 2).value
        Close #1

        myRow = myRow + 1
    End If
Wend
End Sub


Sub url_Test(URL As String, Filename As String)

Dim FSO As Object
Dim ieApp As Object
Dim Txt As String
Dim TxtFile As Object

Set FSO = CreateObject("Scripting.FileSystemObject")
Set TxtFile = FSO.OpenTextFile(Filename, 2, True, -1)

Set ieApp = CreateObject("InternetExplorer.Application")
ieApp.Visible = True
ieApp.Navigate URL

While ieApp.Busy Or ieApp.ReadyState <> 4
    DoEvents
Wend

Txt = ieApp.Document.body.innerText
TxtFile.Write Txt
TxtFile.Close

ieApp.Quit

Set ieApp = Nothing
Set FSO = Nothing
End Sub

你能修复代码中的回车吗?很难确定缺失的回车是问题还是因为你粘贴代码的方式造成的。 - Keith
2
我强烈建议您安装并使用Smart Indent(http://www.oaltd.co.uk/Indenter/),或者努力进行适当的缩进,而不是那样的混乱。 - iDevlop
1个回答

27
在第一个If的行上,在Then之后必须换行,否则你的If将被隐式关闭。
'Good (in this case)
If <condition> Then    
   DoSomething
   myRow = myRow + 1
Else
   DoSomething Different
End if


'NOT good 
If <condition> Then  DoSomething  
   'the if is now "closed" !!!
   myRow = myRow + 1
Else
   DoSomething Different
End if

2
智能缩进器立即突出显示了问题,因为Else没有与If对齐。 - SeanC
+1 我需要帮我弟弟做 QBASIC 的作业,一直在想为什么它不起作用。不过现在看来这很有趣。 - Illegal Argument

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接