2016-05-12 75 views
1

我想使用alter table命令將字段添加到現有的表,代碼重述如下。但是,我在第一個db.execute命令中出現錯誤,提示「定義的字段太多」。此代碼應創建大約(12 + 4)* 3 = 48個新列。是從形式的值如下:(以防萬一):改變表中的循環添加多個字段vba access

  1. me.yearsback = 1
  2. me.valdate = 2016年5月31日
  3. me.period = 「每月」

在這裏需要一些幫助。是否有我應該使用的不同命令或完全不同的方法?

Option Compare Database 

Private Sub EP_Click() 

Dim db As Database 
Dim rs As Recordset 
Dim x As Integer 
Dim y As Integer 
Dim Months As Integer 
Dim WPmonthly As String ' field name for monthly written premium 
Dim UPRmonthly As String ' field name for monthly unearned premium 
Dim EPmonthly As String ' field name for monthly earned premium 
Dim runningDate As Date 
Dim runningDate2 As Date 
Dim useDateLower As Date 
Dim useDateUpper As Date 

Months = Me.YearsBack * 12 + Month(Me.ValDate) 

If Me.Period = "monthly" Then 
    Set db = CurrentDb 
    For x = 1 To Months 
    runningDate = Format(DateAdd("m", -x + 1, Me.ValDate), "mm yyyy") 
    WPmonthly = "WP M" & Month(runningDate) & " " & Year(runningDate) 
    EPmonthly = "EP M" & Month(runningDate) & " " & Year(runningDate) 
    UPRmonthly = "UPR M" & Month(runningDate) & " " & Year(runningDate) 
    db.Execute "ALTER TABLE tblEPdata ADD COLUMN [" & WPmonthly & "] STRING;" 
    db.Execute "ALTER TABLE tblEPdata ADD COLUMN [" & EPmonthly & "] STRING;" 
    db.Execute "ALTER TABLE tblEPdata ADD COLUMN [" & UPRmonthly & "] STRING;" 
    If x = Months Then 
     runningDate = Format(DateAdd("m", -x + 1, Me.ValDate), "mm yyyy") 
     UPRmonthly = "UPR M" & Month(runningDate) & " " & Year(runningDate) 
     db.Execute "ALTER TABLE tblEPdata ADD COLUMN [" & UPRmonthly & "] STRING;" 
    End If 



     Next 
    End If 
     db.Close 

    End Sub 

回答

1

聽起來像一個Access錯誤,它認爲你已經超過了255列限制。請嘗試:

在Microsoft Access 7.0或97中,單擊文件菜單上的另存爲/導出 並以其他名稱保存該表。然後,刪除原始表 表並將其重命名爲新表以原始表名稱。

警告:在版本1.x或2.0 的文件菜單上單擊另存爲僅複製表的結構,而不是記錄。不要刪除 原始表,直到您使用追加查詢來填充新的 表。

https://support.microsoft.com/en-us/kb/128221

0

對於您要添加的,而不是ALTER TABLE使用的每個字段:

db.TableDefs("Your Table").CreateField(your variable,dbtext)