這個答案是姍姍來遲。我修改了here中的代碼,並將其更改爲從本地表複製到SQL Server中的表。
Public Sub CopySchemaAndData_ADOX(ByVal sourceTableName As String, ByVal destinationTableName As String)
On Error GoTo Err_Handler
Dim cn As ADODB.Connection
Dim cat As ADOX.Catalog
Dim cnSQL As ADODB.Connection
Dim catSQL As ADOX.Catalog
Dim sourceTable As ADOX.Table
Dim destinationTable As ADOX.Table
Set cnSQL = New ADODB.Connection
'Set cnSQL = CurrentProject.Connection
cnSQL.Provider = "MSDASQL"
cnSQL.ConnectionString = gstrOLEDBConnection 'put your connection string here. the user needs to be able to create tables on the database
cnSQL.Open
Set catSQL = New ADOX.Catalog
Set catSQL.ActiveConnection = cnSQL
Set destinationTable = New ADOX.Table
destinationTable.Name = destinationTableName
Set cn = CurrentProject.Connection
Set cat = New ADOX.Catalog
Set cat.ActiveConnection = cn
Set sourceTable = cat.Tables(sourceTableName)
Dim col As ADOX.Column
For Each col In sourceTable.Columns
Dim newCol As ADOX.Column
Set newCol = New ADOX.Column
With newCol
.Name = col.Name
.Attributes = col.Attributes
.DefinedSize = col.DefinedSize
.NumericScale = col.NumericScale
.Precision = col.Precision
.Type = col.Type
End With
destinationTable.Columns.Append newCol
Next col
Dim key As ADOX.key
Dim newKey As ADOX.key
Dim KeyCol As ADOX.Column
Dim newKeyCol As ADOX.Column
For Each key In sourceTable.keys
Set newKey = New ADOX.key
newKey.Name = key.Name
For Each KeyCol In key.Columns
Set newKeyCol = destinationTable.Columns(KeyCol.Name)
newKey.Columns.Append (newKeyCol)
Next KeyCol
destinationTable.keys.Append newKey
Next key
catSQL.Tables.Append destinationTable
'To do...
'Link the new sql table
'Finally, copy data from source to destination table
'Dim sql As String
'sql = "INSERT INTO " & destinationTableName & " SELECT * FROM " & sourceTableName
'CurrentDb.Execute sql
Err_Handler:
Set cat = Nothing
Set catSQL = Nothing
Set key = Nothing
Set col = Nothing
Set sourceTable = Nothing
Set destinationTable = Nothing
Set cnSQL = Nothing
Set cn = Nothing
If Err.Number <> 0 Then
msgBox Err.Number & ": " & Err.Description, vbCritical, Err.Source
End If
End Sub
什麼是連接字符串和您使用什麼代碼來創建表? – HelloW
我正在使用MS Access的升遷嚮導 – user3227381
這是一個反覆出現的過程還是一次性場景? – HelloW