Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 外部数据源的简化VBA代码_Sql_Vba_Excel - Fatal编程技术网

Sql 外部数据源的简化VBA代码

Sql 外部数据源的简化VBA代码,sql,vba,excel,Sql,Vba,Excel,因此,在我所有使用SQL查询数据库的VBA宏中,我刚刚使用了在Excel中记录宏时自动输入的内容。有没有办法简化它?它首先将其插入表中,但实际上我只想将原始数据插入电子表格中。。。它不需要好看 Sheets("Sheet1").Select With ActiveSheet.ListObjects.Add(SourceType:=0, Source:="ODBC;DSN=AS400;" _ , Destination:=Range("$A$1")).QueryTable .Com

因此,在我所有使用SQL查询数据库的VBA宏中,我刚刚使用了在Excel中记录宏时自动输入的内容。有没有办法简化它?它首先将其插入表中,但实际上我只想将原始数据插入电子表格中。。。它不需要好看

Sheets("Sheet1").Select
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:="ODBC;DSN=AS400;" _
    , Destination:=Range("$A$1")).QueryTable
    .CommandText = strSQL
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = True
    .ListObject.DisplayName = "Table_LOCAL_ITEM"
    .Refresh BackgroundQuery:=False
End With
ActiveSheet.ListObjects("Table_LOCAL_ITEM").Unlist
Cells.Select
Selection.ClearFormats

我记不起确切的代码了,但我可以在重新开始工作时查找。但是,根据您在SQL中获取数据所使用的方法(例如ADO或DAO),如果我只需要原始数据,我会这样做

如果将变量定义为记录集(例如Dim rst as recordset),VBA具有从记录集中返回所有数据的功能,类似于:

Sheets("Sheet 1").Range("A1").CopyFromRecordset rst

它将输出记录集中的所有数据。

录制任何宏后,使用
Select
Selection
Activesheet
等删除任何内容,除非您主动希望将其用作输入。例如
Cells.Select:Selection.ClearFormats->Cells.ClearFormats
Sheets(“Sheet1”)。Select:With-ActiveSheet->With-Sheets(“Sheet1”)