VBA执行SQL语句有一个固定的套路。
哪怕你连VBA代码一句都看不懂也没关系,只要知道在哪里写入SQL语句就可以了。
代码如下:
Sub DoSql_Execute()Dim cnn As Object, rst As ObjectDim Mypath As String, Str_cnn As String, Sql As StringDim i As LongSet cnn = CreateObject("adodb.connection")Mypath = ThisWorkbook.FullNameIf Application.Version < 12 ThenStr_cnn = "Provider=Microsoft.jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" & MypathElseStr_cnn = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0;Data Source=" & MypathEnd Ifcnn.Open Str_cnnSql = "SELECT * FROM [学生表$]" '//请在此处写入你的SQL代码Set rst = cnn.Execute(Sql)Cells.ClearContentsFor i = 0 To rst.Fields.Count - 1Cells(1, i + 1) = rst.Fields(i).NameNextRange("a2").CopyFromRecordset rst 'cnn.CloseSet cnn = NothingEnd Sub
