总感觉如下代码太过繁琐:Public Function FieldIsInTableOfDatabase(ByVal sFieldName As String, ByVal sTableName As String, ByRef db As Database) As Boolean
                    
    Dim bExists As Boolean
    bExists = False
    
    ' 用DAO对象,逐个读取数据库db的表名,查找数据表sTableName的字段sFieldName是否存在
    Dim objTable As TableDef
    For Each objTable In db.TableDefs
        Debug.Print objTable.Name
        If LCase(objTable.Name) = LCase(sTableName) Then
            bExists = True
            Exit For
        End If
    Next
       
    If bExists Then
        bExists = False
        Dim i As Integer
        For i = 0 To objTable.Fields.Count - 1
            If LCase(objTable.Fields(i).Name) = LCase(sFieldName) Then
                bExists = True
                Exit For
            End If
        Next i
    End If
        
    Set objTable = Nothing
    FieldIsInTableOfDatabase = bExistsEnd Function

解决方案 »

  1.   

    基本上也就是这样做了,如果用ADO,在检测表是否存在时,可以不用循环:通过查询系统表MSysObjects,判断指定表是否存在(需要设置权限:打开Access,工具/选项/视图/选中系统对象,确定后,工具/安全/用户与组权限/对象名称/选中MSysObjects--->权限/读取数据,确定,关闭Access)
    Public Function FieldIsInTableOfDatabase(ByVal sFieldName As String, ByVal sTableName As String, ByRef db As Database) As Boolean
                        
        Dim bExists As Boolean
        bExists = False
        
        Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
        cn.CursorLocation = adUseClient
        cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\Test.mdb;User Id=admin;Password=;"
        rs.Open "SELECT [Name] FROM MsysObjects WHERE [name]= " & sTableName, cn, adOpenDynamic, adLockOptimistic
           
        If Not (rs.BOF And rs.EOF) Then
            bExists = False
            Dim i As Integer
            For i = 0 To rs.RecordCount - 1
                If LCase(rs(i).Name) = LCase(sFieldName) Then
                    bExists = True
                    Exit For
                End If
            Next i
        End If
        
        rs.Close
        cn.Close
        Set rs = Nothing
        Set cn = Nothing
        FieldIsInTableOfDatabase = bExistsEnd Function
      

  2.   

    差不了多少,ADO也是这样的,从访问ACCESS的角度上来说.DAO比ADO强一些,从代码上来说,ADO少几行而已Option ExplicitPublic Rs As New ADODB.Recordset
    Public Conn As New ADODB.ConnectionPrivate Sub Command1_Click()
       On Error Resume Next
       Conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=C:\test.mdb"
       Set Rs = Conn.Execute("Student")     '2
       If Err.Number <> 0 Then
          Debug.Print "Table 不存在"
          Exit Sub
       End If
    End Sub
      

  3.   

    Dim objTable As TableDef
        For Each objTable In db.TableDefs
            Debug.Print objTable.Name
            If LCase(objTable.Name) = LCase(sTableName) Then
                bExists = True
                Exit For
            End If
        Next这段代码,能不能简化一下,让objTable直接打开以sTableName命名的表,而不用通过循环列举表名?我记得VC当中的CDaoTableDef类倒是可以。