宏根据用户单元格选择显示SQL结果

时间:2010-02-23 08:21:06

标签: excel-vba excel sql vba

大家好我有以下代码: 现在这段代码的作用是从SQL查询中获取结果并将它们插入我在代码中指定的预定义单元格...我想要它做什么,。,,是将查询结果插入到当用户点击我在下面指定宏的按钮时,用户选择的单元格。 所以流程将是

  • 用户点击按钮
  • 要求用户选择单元格宏 显示选中的单元格中的结果 用户..

我该怎么做?

Sub Stats1()
Workbooks("2006_2007_2008.xls").Sheets("Sheet1").Select

Dim objConn As ADODB.Connection

Dim rsData As ADODB.Recordset

 Dim strSQL As String 
 szconnect = "Provider=SQLOLEDB;Integrated Security=SSPI;Persist Security             

 Info=False;Initial Catalog=*****;Data Source=*****"

'Create the Connection and Recordset objects.

 Set objConn = New ADODB.Connection

 Set rsData = New ADODB.Recordset

 On Error GoTo errHandler

'Open the Connection and execute the stored procedure

objConn.Open szconnect



 strSQL = "select name from user"

objConn.CommandTimeout = 

Set rsData = objConn.Execute(strSQL)

For iCols = 0 To rsData.Fields.Count - 1

    ActiveSheet.Range().Select
  ActiveSheet.Cells(ActiveCell.Row, ActiveCell.Column + iCols).Value =           rsData.Fields     (iCols).Name
   ActiveSheet.Cells.Font.Name = "Arial"
   ActiveSheet.Cells.Font.Size = 8
  Next
  ActiveSheet.Range(ActiveSheet.Cells(ActiveCell.Row, ActiveCell.Column),     
  ActiveSheet.Cells(ActiveCell.Row, ActiveCell.Column +rsData.Fields.Count)).Font.Bold    = True               


 j = 2

 If Not rsData.EOF Then

'Dump the contents of the recordset onto the worksheet
 On Error GoTo errHandler

ActiveSheet.Cells(ActiveCell.Row + 1, ActiveCell.Column).CopyFromRecordset rsData
If Not rsData.EOF Then
MsgBox "Data set too large for a worksheet!"

End If

rsData.Close
 End If



 Unload frmSQLQueryADO

Exit Sub



 errHandler:

 MsgBox Err.Description, vbCritical, "Error No: " & Err.Number

'Unload frmSQLQueryADO

 End Sub

1 个答案:

答案 0 :(得分:0)

你不知道该怎么办?
vba帮助告诉您如何将宏添加到按钮上。

要让用户输入范围,最简单的就是这个

将my_cell调暗为字符串
my_cell = InputBox(“哪个单元格?”)

或者您可以创建一个用户表单并将RefEdit控件放在表单上。

这是一种方式

Dim my_cell As Range  
Set my_cell = Application.InputBox(prompt:= _  
"Click in a cell to select a destination range", Type:=8)  
my_cell.Select