使用VBA Access 2007以编程方式更改字段类型

时间:2015-12-01 21:11:13

标签: vba ms-access-2007

我有一个例程,可以导入Excel表,更改多个列(字段)名称,添加索引和几个新字段。但是,索引字段从Excel导入为Double,我想将其更改为Long。除了更改类型外,此代码段均可使用:

Set tdf = db.TableDefs(TableName) ' Modify the new MBDA List table
For Each fld In tdf.Fields
    Select Case fld.Name ' Change the name of specific fields
        Case "MBDA Piece ID #"
            fld.Name = "MBDA Piece ID"
            fld.Type = dbLong ' change the type from Double to Long
        Case ">>Grade Level"
            fld.Name = "Grade"
        Case Else
    End Select
Next fld
NumFlds = i

3 个答案:

答案 0 :(得分:3)

表格字段的一部分后,您无法更改表格字段的类型。设置Route::resource('news/{cat}/article', 'ArticleController'); 仅在向表中添加新字段时有效。

您的代码可能会提供"错误3219:无效操作" ?

但您可以使用DDL(数据定义语言)SQL,使用fld.Type - ALTER TABLE语句来执行此操作:

ALTER COLUMN

编辑:这里概述了DDL数据类型名称与DAO常量(例如db.Execute "ALTER TABLE [MBDA List] ALTER COLUMN [MBDA Piece ID] LONG" ):http://allenbrowne.com/ser-49.html

答案 1 :(得分:0)

您可以尝试

Sub AlterDataType()
   Dim strSQL As String
   strSQL = "ALTER TABLE [myTable] ALTER COLUMN myColumnDbl memo"
   DoCmd.RunSQL strSQL
End Sub

答案 2 :(得分:-1)

Sub vRunSetFieldType()

Call vSetFieldType("Reporting Period", "LONG")

End Sub

Sub vSetFieldType(strFld As String, strFldType As String)

Dim db As dao.Database
Dim tbl As TableDef
Dim fld As dao.Field
Dim strSQL As String

Set db = CurrentDb

For Each tbl In db.TableDefs
    If InStr(1, LCase(tbl.Name), "msys") = 0 Then
        For Each fld In tbl.Fields
            If LCase(fld.Name) = LCase(strFld) Then
                'Debug.Print tbl.Name & Chr(9) & fld.Name & Chr(9) & fld.Type
                strSQL = "ALTER TABLE [" & tbl.Name & "] ALTER COLUMN [" & fld.Name & "] " & strFldType & ";"
                Debug.Print strSQL
                db.Execute strSQL
            End If
        Next fld
    End If
Next tbl

End Sub