我在这段代码中一直收到错误,说“如果没有阻止,则结束”。我已经看了它,看不出问题,打印出来并将所有的If语句连接到他们加入的End If,一切看起来都正确。
是否有其他东西抛弃了,比如With With End With block?
Private Sub cmd__Import_Eligibility_Click()
' Requires reference to Microsoft Office 11.0 Object Library.
Dim fDialog As FileDialog
Dim varFile As Variant
Dim filelen As Integer
Dim filename As String
Dim tblname As String
' Set up the File Dialog.
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
fDialog.InitialFileName = "oo*.*"
With fDialog
' Set the title of the dialog box.
.Title = "Please select a file"
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel Spreadsheets", "*.xls*"
.Filters.Add "Comma Separated", "*.CSV"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
'Loop through each file selected and add it to our list box.
varFile = fDialog.SelectedItems(1)
If Right(varFile, 4) = ".xls" Or Right(varFile, 5) = ".xlsx" Then
'get only file name
For a = Len(varFile) To 1 Step -1
If Mid(varFile, 1) = "\" Then
filelen = a
End If
Exit For
filename = Right(varFile, filelen)
tblname = Left(filename, InStr(filename, ".") - 1)
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12, tblname, filename, True
End If 'ERRORS OUT ON THIS LINE ==========================
Else
MsgBox "You clicked Cancel in the file dialog box."
End If
End With
End Sub
答案 0 :(得分:5)
As Scott posted as a comment,您的For...Next
循环结构格式错误:
For a = Len(varFile) To 1 Step -1 If Mid(varFile, 1) = "\" Then filelen = a End If Exit For
没有For...Exit For
循环这样的东西。你的意思是这样做:
For a = Len(varFile) To 1 Step -1
If Mid(varFile, 1) = "\" Then
filelen = a
Exit For
End If
Next
否则编译器会看到[大致]这个:
If [bool-expression] Then
For [for-loop-setup]
If [bool-expression] Then
[instructions]
End If
Exit For
[instructions]
End If '<~ expecting "Next" before that "End If" token.
我认为,运行自动压头会使这个问题变得明显。我碰巧管理一个开源项目,将流行的 Smart Indenter VBE加载项移植到.NET,以便它可以在64位环境中运行。有关所有功能,请参阅rubberduckvba.com。