Excel VBA到没有SSIS的SQL Server

Excel问题:用户单击button,VBAparsinginput文件,将数据放入电子表格的单元格中。 然后,她将电子表格的副本邮寄给使用数据的人员。

我将用SSRS或ASP或Sharepointreplace此显示来自SQL Server的数据。

为了在不中断当前进程的情况下处理这个问题,我想要Excel VBA,每次向电子表格写入一行时,还要通过存储的proc将其插入到SQL Server数据库中。

可以让它将CSV中的行写入一个文件,以便稍后SSIS导入,但是我宁愿直接转到数据库。

我知道如何在VB.Net中做到这一点,但我从来没有在VBA中写入数据(通常是数据入logging集,但没有写入)。

我宁愿将值作为params传递给存储过程,但是如果必须的话,我可以为每一行生成较慢的INSERT命令。

从VBA开始,最简单的数据访问库就是ADO。 添加对“Microsoft ActiveX数据对象库”的引用,以便您可以使用ADODB。*对象。

要执行存储过程(在你的情况下将添加一个logging到表),你可以这样做:

懒惰的方式(直接创buildSQL语句,不使用Parameter对象;这很容易导致SQL注入攻击):

Public Sub AddFoo _ ( _ strServer As String, _ strDatabase As String, _ strUsername As String, _ strPassword As String, _ lFooValue As Long _ ) ' Build the connection string Dim strConnectionString As String strConnectionString = "Driver={SQL Server}" _ & ";Server=" & strServer _ & ";Database=" & strDatabase _ & ";UID=" & strUsername _ & ";PWD=" & strPassword ' Create & open the connection Dim oConnection As Connection Set oConnection = New Connection oConnection.ConnectionString = strConnectionString oConnection.Open ' Build the SQL to execute the stored procedure Dim strSQL As String strSQL = "EXEC AddFoo " & lFooValue ' Call the stored procedure Dim oCommand As Command Set oCommand = New Command oCommand.CommandType = adCmdText oCommand.CommandText = strSQL oCommand.ActiveConnection = oConnection oCommand.Execute oConnection.Close End Sub 

…或正确的方式(处理所有参数的编码,因此不容易受到SQL注入攻击 – 无论是故意的还是意外的):

 Public Sub AddFoo _ ( _ strServer As String, _ strDatabase As String, _ strUsername As String, _ strPassword As String, _ lFooValue As Long _ ) ' Build the connection string Dim strConnectionString As String strConnectionString = "Driver={SQL Server}" _ & ";Server=" & strServer _ & ";Database=" & strDatabase _ & ";UID=" & strUsername _ & ";PWD=" & strPassword ' Create & open the connection Dim oConnection As Connection Set oConnection = New Connection oConnection.ConnectionString = strConnectionString oConnection.Open ' Build the SQL to execute the stored procedure Dim strSQL As String strSQL = "EXEC AddFoo " & lFooValue ' Create the command object Dim oCommand As Command Set oCommand = New Command oCommand.CommandType = adCmdStoredProc oCommand.CommandText = "AddFoo" ' Create the parameter Dim oParameter As Parameter Set oParameter = oCommand.CreateParameter("foo", adParamInteger, adParamInput) oParameter.Value = lFooValue oCommand.Parameters.Add oParameter ' Execute the command oCommand.ActiveConnection = oConnection oCommand.Execute oConnection.Close End Sub 

你如何使用VBA读取数据?

如果您使用ADOlogging集:查看ADODB.Command类; 这允许您执行SQL或存储过程并将parameter passing给它(Google for ado命令示例 )。

如果您使用DAOlogging集:您的DAO数据库的Execute方法允许您执行SQL语句。

从长远来看,人们终于开始接受一种更好的方式:自动化(而不是button点击)直接将文件读入数据库(SSIS),需要数据的人员可以查看报告而不是通过电子邮件发送的Excel文件。