简体   繁体   English

MS Access 数据库使用 vba 和 sql 查询在列上插入值

[英]MS Access Database insert values on a column using vba and sql query

Is there any way to add a column into an MS Access database using VBA and SQL query and then insert values using formulas from other column.有什么方法可以使用 VBA 和 SQL 查询将列添加到 MS Access 数据库中,然后使用其他列中的公式插入值。

As an example, I want to create a column employee and it should have calculated values on all the records.例如,我想创建一个列employee ,它应该对所有记录计算值。 I want to use LEFT(col2, 3) in the employee field.我想在employee字段中使用LEFT(col2, 3)

This is my code:这是我的代码:

Sub createcolumn()
    Dim objAccess As Object
    Set objAccess = CreateObject("Access.Application")
    Call objAccess.OpenCurrentDatabase("H:\VBA\Array Practice\Database1array.accdb")
    objAccess.CurrentProject.Connection.Execute ("ALTER TABLE Company ADD COLUMN employee CHAR ")
End Sub
Sub insertvalues()
    Dim objAccess As Object
    Set objAccess = CreateObject("Access.Application")
    Call objAccess.OpenCurrentDatabase("H:\VBA\Array Practice\Database1array.accdb")
    objAccess.CurrentProject.Connection.Execute "INSERT INTO Employee (Gross) VALUES LEFT([full_name], 3)"
End Sub

I am able to create a new column but could't insert the value.我能够创建一个新列,但无法插入该值。

You can directly update the table using column FULL_NAME instead of inserting.您可以使用列 FULL_NAME 而不是插入直接更新表。 I have tested the following code and it is working.我已经测试了以下代码并且它正在工作。

Sub test()
Dim dbs As Database
Set dbs = OpenDatabase("Database1.accdb")  
dbs.Execute "UPDATE EMPLOYEE SET GROSS=LEFT(FULL_NAME, 3)"
dbs.Close
End Sub

You added a column to a table named Company, but you are attempting to insert values to a table named employee.您向名为 Company 的表添加了一列,但您正尝试向名为 employee 的表插入值。

If the table named company as records then an update statement is what you need to add values into the new column employee, but if the table does not have any record, then an insert statement can be used to add values into the employee field.如果表名为 company 作为记录,那么您需要更新语句将值添加到新列员工中,但如果表没有任何记录,则可以使用插入语句将值添加到员工字段中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM