使用VBA和&amp ;;确定错误的输入文件高强

时间:2009-09-28 14:44:11

标签: excel excel-vba vba

有关确定用户选择的Excel文件是否不正确的建议吗?我让用户选择要解析的excel文件,如果看起来格式不正确,我想拒绝处理它。

3 个答案:

答案 0 :(得分:0)

在excel文件中放入隐藏版本字段或其他字符串,如果字符串不匹配则中断执行。当然假设您可以控制文件或模板,从中创建文件。

答案 1 :(得分:0)

如果要解析的文件有标题,请检查一些文本。

Sub ImportXYZ()

' ... Code to import

 If ActiveWorkbook.Worksheets("Sheet1").Range("A1") <> "XYZ" Then
  MsgBox CStr(ActiveWorkbook.Name) & vbCr & _
  "The file you selected does not contain XYZ data!" & vbCr & "Please try again."

' ... Code to reset

  Call ImportXYZ

 End If

' ... Code to process import

End Sub

答案 2 :(得分:0)

作为在工作表中放置标识正确文件类型的标记的替代方法,您还可以使用工作簿属性。创建自定义属性“MyExcelFilesClassification”,并为属性赋予类似“MyTypeOfWorkbook”的值。当您的代码打开文件时,请检查该属性是否具有正确的值,例如:

Office.DocumentProperties customProperties = workbook.CustomDocumentProperties as Office.DocumentProperties;
     foreach (Office.DocumentProperty property in customProperties)
     {
        if (property.Name == "MyExcelFilesClassification")
        {
           string modelType = property.Value as string;
           if (modelType == "MyTypeOfWorkbook")
           {
              // do something
           }
        }
     }

这是C#代码,但VBA或VB语法不应该有很大不同。