从sql运行sql查询到excel

时间:2014-03-29 00:08:09

标签: sql excel vba

我已经录制了一个宏,它基本上从excel中运行sql查询并将数据粘贴到工作表中。然而,问题是当数据被粘贴到表格中时数据顺序失真。例如,我从Range(" B3")开始粘贴sql查询,但如果在查询后我在单元格D4中有其他数据,则此数据无缘无故地移动到单元格F4。我在表单上获得的所有其他数据也是如此。换句话说,在粘贴sql查询的结果后,单元格数据的顺序会失真。我该如何解决?

    With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
    "ODBC;Driver=MySQL ODBC 5.1    
     Driver;SERVER=localhost;UID=root;DATABASE=second;PORT=3306" _
    , Destination:=Range("$B$4")).QueryTable
    .CommandText = Array( _
    "SELECT employees_0.eid, employees_0.ename, employees_0.age" & Chr(13) & "" & 
    Chr(10) & "FROM second.employees employees_0" _
    )
    .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_Query1"
    .Refresh BackgroundQuery:=False
    End With
   End Sub

1 个答案:

答案 0 :(得分:1)

我相信你的问题是:

.RefreshStyle = xlInsertDeleteCells

应该是:

.RefreshStyle = xlOverwriteCells

您可以阅读有关方法here的更多信息。