嵌套If Then和For语句

时间:2018-06-01 23:24:06

标签: excel vba excel-vba

我知道如何修复下面的宏中的错误,但不知道修复背后的原因。为什么“_”在第二个If ... Then语句中导致问题?

我可以通过删除“_”或在其下方插入一行来修复它。但是,我无法将For语句移动到If ... Then语句的末尾。

Sub Loop_Link_Change_ROE()

Dim MyPath As String
Dim MyFile As String
Dim sLink As String
Dim sNewName As String
Dim tNewName As String
Dim varLinks As Variant
Dim i As Integer

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

MyPath = "P:\Department\Actuarial Archive\Reserves\2018Q2\Documentation\Data Recon\"
MyFile = Dir(MyPath)

Do While MyFile <> ""
If MyFile Like "*Analysis_Regions_Phys_CM_*.xl*" Then
Workbooks.Open Filename:=MyPath & MyFile, UpdateLinks:=0

varLinks = ActiveWorkbook.LinkSources(xlExcelLinks)

If Not IsEmpty(varLinks) Then _
For i = 1 To UBound(varLinks)

    If InStr(1, varLinks(i), "4Q17") Then sNewName = Replace(varLinks(i), "4Q17", "2Q18")
    If InStr(1, varLinks(i), "GA") Then tNewName = Replace(sNewName, "GA", "Mid(varLinks(i), 30, 2)")
    If InStr(1, varLinks(i), "GA") Then ActiveWorkbook.ChangeLink Name:=varLinks(i), NewName:=tNewName, Type:=xlExcelLinks

ActiveWorkbook.Close True

Next

End If

End If

MyFile = Dir

Loop

Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

End Sub

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

在VBA中使用If有两种基本形式

所有一行:

If {test} Then {something}

...在这种情况下,后续行与If

无关

使用End If和多行:

If {test} Then
   {something} 'one or more lines of code
End If

你的_没有做任何有用的事情

答案 1 :(得分:1)

Underscore是vb中的一个行继续,所以如果你使用它,那么你不需要if if语句的“end if”,因为下面的for循环行被视为它是前一行的一部分。