2017-06-13 126 views
2

我有一個電子表格來調用SQL Server存儲過程並返回數據。在Excel 2010中工作100%,並且已經完成數月。但是,對於Excel 2013中的某些用戶,它不會返回所有數據 - 它只會通過0來返回。這裏是我的代碼:Excel 2010 vs Excel 2013 VBA存儲過程

Sub Button10_Click() 
    Set con = New ADODB.Connection 
    Set cmd = New ADODB.Command 
    Set rs = New ADODB.RecordSet 

    Sheets("Customer").Visible = True 

    'Unprotect worksheet 
    Worksheets("Customer").Unprotect Password:="*******" 

    ' remove and re-add auto filter 
    Sheets("Customer").AutoFilterMode = False 
    Sheets("Customer").Range("A4:AO4").AutoFilter 

    Application.DisplayStatusBar = True 
    Application.StatusBar = "Contacting SQL Server..." 

    ' Remove any values in the cells where we want to put our Stored Procedure's results. 
    With Sheets("Customer") 
     .Rows(5 & ":" & .Rows.Count).Delete 
    End With 

    ' Log into our SQL Server, and run the Stored Procedure 
    con.Open "Provider=SQLOLEDB;Data Source=*********;Initial Catalog=**********;Integrated Security=SSPI;Trusted_Connection=Yes;" 
    cmd.ActiveConnection = con 

    Application.StatusBar = "Running stored procedure..." 

    '===== Check if the user has ticked the 'Include Current Month Totals checkbox ==== 
    If Range("$M$1") = True Then 
     'include current month in totals 
     cmd.CommandText = "usp_Customer_Lvl1_Current_Month_INC"  
    Else 
     'do not include current month in totals 
     cmd.CommandText = "usp_Customer_Lvl1_Previous_Month_INC" 
    End If 

    Set rs = cmd.Execute(, , adCmdStoredProc) 

    '========== 
    Sheets("Customer").Range("A5").CopyFromRecordset rs 
    Application.Goto Reference:=Worksheets("Customer").Range("A5") 

    'protect worksheet 
    Worksheets("Customer").Protect Password:="***********", AllowFormattingCells:=True, AllowFiltering:=True 

    '============= 

    rs.Close 
    Set rs = Nothing 
    Set cmd = Nothing 

    con.Close 
    Set con = Nothing 

    Application.StatusBar = "Data successfully updated." 
End Sub 

它必須是在VBA中的東西。數據存在於SQL和Excel 2010中 - 任何想法?

+0

是否有任何錯誤信息? –

+0

不 - 無 - 它只是不返回所有的數據 - 非常奇怪 – Michael

+0

檢查我[過去的回答](https://stackoverflow.com/questions/28677262/recordset-closed-after-stored-procedure-execution)。您可能會發現有關SP的非常有用的信息。 –

回答

0

我解決了它。我從文本框中獲取一個值。在Excel 2010中我只是用下面的:

如果範圍( 「$ M $ 1」)= TRUE然後

然而,在Excel 2013會出現它,你還需要引用工作表,以及:

如果表格(「Home」)。Range(「$ M $ 1」)= True然後

無論如何,包括表格名稱現在意味着它的工作原理。