如果没有结束则阻止if和Next没有结束

时间:2015-02-03 02:58:44

标签: excel vba

Dim GroupChoice, MEGChoice, StudentName, group1Late, MEG1Late As String

'Making the link variables equal to the cell link for the combo boxes
GroupLink = Range("LateGroup")
MEGlink = Range("LateMEG")
'loop to find which choice the user has picked for their group
If GroupLink = 1 Then
    MsgBox "You have not selected a group", vbOKOnly
    Exit Sub
Else
If GroupLink = 2 Then
    GroupChoice = "1"
Else
If GroupLink = 3 Then
    GroupChoice = "2"
End If
'loop to find which choice the user has picked for their MEG
If MEGlink = 1 Then
    MsgBox "you have not selected a MEG for the new student", vbOKOnly
Else
If MEGlink = 2 Then
    MEGChoice = "A"
Else
If MEGlink = 3 Then
    MEGChoice = "B"
Else
If MEGlink = 4 Then
    MEGChoice = "C"
Else
If MEGlink = 5 Then
    MEGChoice = "D"
Else
If MEGlink = 6 Then
    MEGChoice = "E"
End If

StudentName = Range("Studentname")
Sheets("unit 1").Select

If GroupChoice = 1 Then
    For row = 1 To 15
        group1Late = "A" & row
        MEG1Late = "AD" & row
        If ActiveSheet.Cells(row, 1).Value = "" Then
            Range("group1Late") = StudentName
            Range("MEG1Late") = MEGChoice
        End
    Next
End
End Sub

这是一个大学项目,我需要宏来运行并检查15中的空白区域(这需要稍后重复)然后需要将MEG和学生名称输入到该单元格中。我遇到的问题是,使Next工作的For Loop可能不在正确的位置或IDK。它只是拒绝工作,当我将其取出并将其替换为End时,End Su b会出现block if without end if错误。请帮忙。

2 个答案:

答案 0 :(得分:5)

对于if-without-end问题,如果您使用else if(两个字),每个 if都需要相应的end if。您应该使用elseif(单字)变体作为您编码的方式。看看这两者之间的区别:

if a = 1 then          if a = 1 then
    b = 2                  b = 2
else                   elseif a = 2 then 
    if a = 2 then          b = 1
        b = 1          else
    else                   b = 0
        b = 0          end if
    end if
end if

对于next-without-for问题,您应该使用end if来关闭if语句,而不仅仅是end当前的语句:

If GroupChoice = 1 Then
    For row = 1 To 15
       group1Late = "A" & row
       MEG1Late = "AD" & row
       If ActiveSheet.Cells(row, 1).Value = "" Then
           Range("group1Late") = StudentName
           Range("MEG1Late") = MEGChoice
       End If ' <-- HERE '
    Next
End If        ' <-- AND HERE '

End本身用于停止程序。

我怀疑错误是由for-nextif-end if的不平衡性引起的,VB看到它们是交错的,因为没有end if所以它假定它来到某个地方之后 next

答案 1 :(得分:0)

你可以在这里简化逻辑1..6是序数,就像A..E

一样
If MEGlink = 1 Then
    MsgBox "you have not selected a MEG for the new student", vbOKOnly
Else
    MEGChoice = Chr$(63 + MEGlink) '//generate character
End If