SQL查询来优化电子表格使用vbamacros

我有问题将SQL Server数据带到Excel中。

所以任何人都可以帮助我如何连接到SQL Server使用VBAmacros? 以及如何使VBA脚本SQL查询到Excel电子表格?

谢谢。

在Office 2007中,转到“ 数据”选项卡,然后单击“ 获取外部数据”,您将看到连接到SQL的选项,并在2010年转到“ 数据”选项卡,然后单击“ 其他现有源” ,然后select“ SQL Server” 。 这是将数据拉入工作表来直接操作。

仅在VBA中

在VBA脚本编辑器中包含ActiveX Data Objects参考

以下是有关如何从VBA连接到SQL的代码示例

Sub Connect2SQLXpress() Dim oCon As ADODB.Connection Dim oRS As ADODB.Recordset Set oCon = New ADODB.Connection oCon.ConnectionString = "Driver={SQL Native Client};Server=.\SQLEXPRESS;Database=DB1; Trusted_Connection=yes;" oCon.Open Set oRS = New ADODB.Recordset oRS.ActiveConnection = oCon oRS.Source = "Select * From Table1" oRS.Open Range("A1").CopyFromRecordset oRS oRS.Close oCon.Close If Not oRS Is Nothing Then Set oRS = Nothing If Not oCon Is Nothing Then Set oCon = Nothing End Sub 

要在Excel中启用Visual Basic编辑器,请阅读以下链接以启用“开发人员”选项卡

这应该提供您所需要的快速概览。