[英]adding new field to table in access using vba
I get an error in the line with the alter table command. 我在alter table命令行中遇到错误。 I'm trying to create a field for each month based on the variable monthly using a loop, however it is not going through since I don't get the desired result.
我正在尝试使用循环基于变量每月为每个月创建一个字段,但是由于我没有得到所需的结果,所以它没有通过。 The code creates a column called monthly and then gives an error on the second iteration.
代码创建一个名为monthly的列,然后在第二次迭代时给出错误。 Code is as follows:
代码如下:
Dim x As Integer
Dim Months As Integer
Dim monthly As String
Months = Me.YearsBack * 12
Set db = CurrentDb
If Me.Period = "monthly" Then
For x = 1 To 2
'Months
monthly = "WP M" & x
db.Execute "ALTER TABLE tblEPdata ADD COLUMN [monthly] string;"
Next
End If
[monthly]
is simply part of the string you are executing, it is not automatically resolved from the variable with the same name. [monthly]
只是您正在执行的字符串的一部分,它不会自动从具有相同名称的变量中解析出来。
You need string concatenation: 你需要字符串连接:
Dim S As String
S = "ALTER TABLE tblEPdata ADD COLUMN [" & monthly & "] string;"
Debug.Print S
db.Execute S
Debug.Print
helps with debugging, the output goes to the Immediate window (Ctrl+G). Debug.Print
有助于调试,输出进入立即窗口(Ctrl + G)。
Notice the syntax coloring in the above code. 请注意上面代码中的语法着色。
"ALTER TABLE tblEPdata ADD COLUMN ["
is a constant string. 是一个常量字符串。
&
concatenates strings and variables into a new string. &
符连接字符串和变量到一个新的字符串。
The [square brackets] are needed because your field names contain spaces (eg WP M2
). 需要[方括号],因为您的字段名称包含空格(例如
WP M2
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.