【问题标题】:VBA and Excel MacroVBA 和 Excel 宏
【发布时间】:2015-02-26 05:18:38
【问题描述】:

VBA 很新,而且在互联网上似乎没有太多帮助,因为我知道它是相对旧的。

我正在尝试使用宏将数据从 Excel 工作表提交到 SQL 服务器数据库。

基本上单击一个按钮,应该从单元格中提取所需的数据,然后将数据放在我的数据库中的正确列中。

它没有正确提交数据,例如一个单元格中有数字“2”,它正在将数字“0”提交到我的数据库中。

谁能给点建议?

代码如下。

' Create the connection string.
sConnString = "provider=xxx; Data Source=xx-xxx; Initial Catalog=xxx;User ID= xx; Password=xxx;": MsgBox "Connection Succesful"



' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
Dim val As String
val = Range("D5").Value

' Open the connection and execute.
conn.Open sConnString

Dim item As String
item = "INSERT INTO [Industrial].[dbo].[Header]("
item = item & "  [server_name]"
item = item & "  ,[date]"
item = item & "  ,[amendee]"
item = item & "  ,[ip_address]"
item = item & "  ,[physical_location]"
item = item & "  ,[host_name]"
item = item & "  ,[is_it_contact]"
item = item & "  ,[businesscontact]"
item = item & "  ,[businessdependencies]"
item = item & "  ,[backup_strategy_in_place]"
item = item & "  ,[physorvirt]"

item = item & "  )Values("
item = item & "  '" & val & "'"
item = item & "  '" & val & "'"
item = item & "  '" & val & "'"
item = item & "  '" & val & "'"
item = item & "  '" & val & "'"
item = item & "  '" & val & "'"
item = item & "  '" & val & "'"
item = item & "  '" & val & "'"
item = item & "  '" & val & "'"
item = item & "  '" & val & "'"
item = item & "  '" & val & "'"

conn.Execute item    

结束子

【问题讨论】:

  • 看起来您正在使用在 D5 中找到的相同值并将其设置为数据库记录的每一列的值。这是您想要的吗?
  • 只是试图将“D5”单元格值添加到属于 [header] 表的 ,[ip_address] 列。

标签: excel vba


【解决方案1】:

您可能需要检查数据库表上的数据类型和约束。它可能取决于您的数据库类型(MySQL、MSSQL 或 Postgres),如果您尝试为布尔列输入“true”而不是 true,它将默认为 0。

其次,我注意到您将相同的值放入每一列。

我可以建议一个数组。 (excel vba 数组简介:http://excelvbatutor.com/vba_chp21.htm

假设您的数据在 Sheet1 上,下面的代码将起作用,就像这样...... A B(列) 1
2 column_name_B “五十” 3 列名_C 10 4 column_name_D 我的名字 (行) 子testeroo()

Dim myArray(2, 2)
Dim x As Integer

Sheets("Sheet1").Activate
For x = 2 To 4
    myArray(x - 2, 0) = Cells(x, 1).Value  'gets the title
    myArray(x - 2, 1) = Cells(x, 2).Value  'gets the value
Next x

然后你可以循环遍历数组来获取你的 SQL 语句。 结束子

【讨论】:

  • 虽然你的回答很好!...我设法让它工作了一夜。
  • 创建 Connection 和 Recordset 对象。 Set conn = New ADODB.Connection Set rs = New ADODB.Recordset Dim val As String val = Range("B5").Value ' 打开连接并执行。 conn.Open sConnString Dim item As String item = "INSERT INTO [IndustrialComp].[dbo].[Header](" item = item & " [server_name]" item = item & " )Values(" item = item & " ' " & val & "')" conn.执行项
猜你喜欢
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-10
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多