excel - VBA excel宏

标签 excel vba

我在 Excel 中有这个 VBA 宏。当用户单击工作表上的按钮时,宏会将结果返回到工作表。
我想问的是,如何使用下面的代码在同一张表中运行多个查询(返回不同的结果)?

Sub Stats2()
  Workbooks("macro.xls").Sheets("Sheet3").Select
  ActiveSheet.Range("A1").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=*******88;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 * from CATEGORY_TYPE  "
  objConn.CommandTimeout = 0
  Set rsData = objConn.Execute(strSQL)

  For iCols = 0 To rsData.Fields.Count - 1
    ActiveSheet.Range("A3").Select
    ActiveSheet.Cells(ActiveCell.Row, ActiveCell.Column + iCols).Value = rsData.Fields(iCols).Name
    ActiveSheet.Cells.Font.Name = "Arial"
    ActiveSheet.Cells.Font.Size = 8
    ActiveSheet.Cells.EntireColumn.AutoFit
  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

最佳答案

您应该从上级程序中准确调用此过程,将查询和起始单元格作为参数传递,您可以按照您的需要多次运行它来填充工作表。

小例子:

sub stats2()
    dim lastrow as string
    lastrow = "A1"
    lastrow = Query1(lastrow,"select * from foo")
    lastrow = Query1(lastrow,"select * from other")
end sub

sub query1(startingrow as string, sqlquery as string) as string
    'your code here. Take in mind that you can have a connection opened outside of here
    'The rest could be the same
    'just use the two parameters, one for the query, the other for the range you 
    'start filling the columns name.
    [code here]
    'return the las used row.
end sub

关于excel - VBA excel宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2222470/

相关文章:

sql-server - Excel 的参数化查询

excel - 将唯一值复制并粘贴到具有多个筛选条件的另一个工作表的最后一个空行中

excel - 选择或复制三个不相邻的单元格 3

java - 更改路径后,VB 脚本未执行 我看到 Windows 脚本主机提示符具有不同的路径

excel - 提取然后将 Csv.gz 文件导入 Excel/SPSS...识别文本限定符有问题吗?

java - 处理 Apache POI 上 Excel 控件的状态

vba - Excel VBA - PDF 文件属性

vba - Excel VBA : Find empty cell and delete the row

excel - Excel Range 奇怪行为的 SpecialCells 方法

vba - 在选择上使用 VBA 设置类别在 Outlook 2007 中似乎不起作用