我正在尝试使用以下代码验证用户上传的文件。错误处理程序检查上传文件的顶行是否有三个特定的列名。如果一个或多个列名不存在,程序应向用户返回提示,通知他们上传的文件中缺少哪些列,然后关闭文件。
我正在寻求帮助的当前 VBA 代码存在几个问题:
- 提示未指定用户缺少哪些列。
- 即使上传的文件中存在所有必需的列,也会触发错误处理程序。
代码:
Sub getworkbook()
' Get workbook...
Dim ws As Worksheet
Dim filter As String
Dim targetWorkbook As Workbook, wb As Workbook
Dim Ret As Variant
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = ".xlsx,.xls"
caption = "Please select an input file "
Ret = Application.GetOpenFilename(filter, , caption)
If Ret = False Then Exit Sub
Set wb = Workbooks.Open(Ret)
On Error GoTo ErrorLine:
'Check for columns
var1 = ActiveSheet.Range("1:1").Find("variable1", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True).Column
var2 = ActiveSheet.Range("1:1").Find("variable2", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True).Column
var3 = ActiveSheet.Range("1:1").Find("variable3", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=True).Column
ErrorLine: MsgBox ("The selected file is missing a key data column, please upload a correctly formated file.")
If Error = True Then ActiveWorkSheet.Close
wb.Sheets(1).Move Before:=targetWorkbook.Sheets("Worksheet2")
ActiveSheet.Name = "DATA"
End Sub