Excel从SQL Server源下拉值

我想从SQL Server中获取Excel中的单元格下拉值。 我不想用所有的数据到另一个工作表和使用数据validation来控制下拉值的方法。 这总是给我一大堆空白的线,因为我想确保我在DB中有任何增加的空间。

有没有办法直接从SQL Server检索下拉值? 使用一个像这样的语句:

Select name from employees 

谢谢你的帮助…

使用ADODB检索所需的值,并使用检索到的值在Excel中填充可以dynamic创build的下拉形状。

在类似的情况下,由于源数据基本上是静态的,因此当应用程序启动时,我使用ADODBlogging集填充全局数组,并在下拉菜单中填充项时使用该数组。 以下是该代码的一个片段:

 Dim InstrumentIDs() As String Dim InstrumentIDReader As Integer Dim InstrumentIDCount As Integer Public PositionRange As String Public Sub GetInstrumentIDs() ' 'Populate InstrumentIDs array from current contents of Instrument table in EMS database ' Dim conn As New ADODB.Connection Dim rs As New ADODB.Recordset Dim sql As String Dim loader As Integer, sn As String InstrumentIDReader = 0 On Error GoTo GetInstrumentError conn.ConnectionString = "Provider=sqloledb; Data Source=myServer; Initial Catalog=myDatabase; User ID=myUser;Password=myPassword" conn.Open sql = "Select Count([SerialNo]) As [Number] From [Instrument]" rs.Open sql, conn, adOpenStatic InstrumentIDCount = CInt(rs![Number]) ReDim InstrumentIDs(InstrumentIDCount - 1) rs.Close sql = "Select [SerialNo] From [Instrument] Order By [SerialNo]" rs.Open sql, conn, adOpenForwardOnly loader = 0 rs.MoveFirst Do While Not rs.EOF sn = CStr(rs![SerialNo]) InstrumentIDs(loader) = sn loader = loader + 1 rs.MoveNext Loop rs.Close conn.Close Set rs = Nothing Set conn = Nothing Exit Sub GetInstrumentError: MsgBox "Error loading instruments: " & Err.Description End Sub 

您必须从VBA编辑器中的工具>参考设置对Microsoft ActiveX Data Objects mn Library的引用(我的计算机上的最新版本为2.8)。

有关如何在Excel中pipe理下拉框的提示,请参见http://www.thespreadsheetsguru.com/blog/2014/5/14/vba-for-excels-form-control-combo-boxes

您可以在Excel中使用MS Query Wizard来存储查询并随时使用它的数据。

这个链接的详细信息http://www.techrepublic.com/article/use-excels-ms-query-wizard-to-query-access-databases/