2017-04-18 46 views
2

我想解決如何使用Access 2016中的創建表子添加一個控件屬性設置爲組合框的字段。訪問2016創建組合框的字段屬性

使用代碼我從各種來源蒐集到的代碼,除了創建組合框之外,我設法運行以下代碼。

表本身需要設置組合框,因爲它最終會上傳到SharePoint。

請幫忙?

Sub maketable() 
Dim db As DAO.Database 
Dim myTable As DAO.TableDef 
Dim myField As DAO.Field 

    Set db = CurrentDb 

    Set myTable = db.CreateTableDef("TestTable") 
     With myTable 
     .Fields.Append .CreateField("DateD", dbDate) 
     .Fields.Append .CreateField("Description", dbText) 
     .Fields.Append .CreateField("Num1", dbDouble) 
     .Fields.Append .CreateField("Num2", dbDouble) 
     .Fields.Append .CreateField("yesno", dbBoolean) 
     .Fields.Append .CreateField("listme", dbText) 
    End With 

    db.TableDefs.Append myTable 

    Set myField = myTable.Fields("DateD") 
    Call SetDAOProperty(myField, "Format", dbText, "Short Date") 

    Set myField = myTable.Fields("Num1") 
    Call SetDAOProperty(myField, "DecimalPlaces", dbByte, 2) 
    Call SetDAOProperty(myField, "Format", dbText, "Standard") 

    Set myField = myTable.Fields("listme") 
    Call SetDAOProperty(myField, "DisplayControl", dbText, acComboBox) 
    Call SetDAOProperty(myField, "RowSourceType", dbText, acvaluelist) 
    Call SetDAOProperty(myField, "RowSource", dbText, "Test1;Test2") 

    Application.RefreshDatabaseWindow 

    Set myField = Nothing 
    Set myTable = Nothing 
    Set db = Nothing 

End Sub 

Function SetDAOProperty(_ 
    WhichObject As Object, _ 
    PropertyName As String, _ 
    PropertyType As Integer, _ 
    PropertyValue As Variant _ 
) As Boolean 
On Error GoTo ErrorHandler 

Dim prp As DAO.Property 

    WhichObject.Properties(PropertyName) = PropertyValue 
    WhichObject.Properties.Refresh 
    SetDAOProperty = True 

Cleanup: 
    Set prp = Nothing 
    Exit Function 

ErrorHandler: 
    Select Case Err.Number 
     Case 3270 ' "Property not found" 
      Set prp = WhichObject.CreateProperty(_ 
       PropertyName, _ 
       PropertyType, _ 
       PropertyValue _ 
      ) 
      WhichObject.Properties.Append prp 
      WhichObject.Properties.Refresh 
      SetDAOProperty = True 
     Case Else 
      MsgBox Err.Number & ": " & Err.Description 
      SetDAOProperty = False 
    End Select 
    Resume Cleanup 

End Function 

回答

1

就快,需要只有兩個變化:

1.

Call SetDAOProperty(myField, "DisplayControl", dbText, acComboBox) 

DisplayControl不是文字而是一個整數屬性:

Call SetDAOProperty(myField, "DisplayControl", dbInteger, acComboBox) 

2 。

這裏VBA編輯器已經提供了一個暗示,有一個問題:

Call SetDAOProperty(myField, "RowSourceType", dbText, acvaluelist) 

acvaluelist不存在。 RowSourceType是一個文本屬性,則correct assignment是:

Call SetDAOProperty(myField, "RowSourceType", dbText, "Value List") 

注:第二屆一個本來具有 Option Explicit在每個模塊的頂部回升。 它在編譯時執行變量聲明並報告未聲明或拼寫錯誤的變量/常量。

要在新模塊中自動執行此操作,請在VBA編輯器中設置Require Variable Declaration選項。 這對VBA開發來說確實是必須的。

+0

安德烈,你是我的英雄,它工作完美,謝謝! –

+1

如果答案解決了您的問題,您可以[接受](http://stackoverflow.com/help/someone-answers)它,這也標誌着問題已解決。 @JimTavolaro – Andre