我正在尝试连接到SQL数据库并根据条件查询数据并将输出提取到Excel工作表中
我在SQL Server中有Web分析数据库,其中包含3个列,分别是页面,综合浏览量和日期信息。
我有一个范围为(A:A)的页面列表,其中包含B1和C1单元格中的日期和日期。
到目前为止,我已经能够通过sql查询过滤一页,如何遍历整个A列并将值传递到SQL查询中的where条件。
下面是我试图连接到sql并提取数据的Excel VBA代码
Sub ga()
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
Dim newrow As String
'Open Connection'
objMyConn.ConnectionString = "Provider=SQLOLEDB; " & "Data Source= xyz\SQLEXPRESS02; " & "Initial Catalog=GA;" & "User ID=uid; Password=pwd; Trusted_Connection=yes"
objMyConn.Open
newrow = "("
For i = 1 To Worksheets("Sheet1").Cells(Worksheets("Sheet1").Rows.Count, "A").End(xlUp).Row
newrow = newrow & "'" & Trim(Worksheets("Sheet1").Cells(i, "A").Value) & "',"
Next i
newrow = Left(newrow, Len(newrow) - 1)
newrow = newrow & ")"
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = "select sum(pageviews),sum(sessions), sum(Bounces)/sum(sessions) as gfdfd from GA1 where page LIKE '" & Range("A1").Value & "'"
objMyCmd.CommandType = adCmdText
objMyCmd.Execute
'Open Recordset'
Set objMyRecordset.ActiveConnection = objMyConn
objMyRecordset.Open objMyCmd
'Copy Data to Excel'
ActiveSheet.Range("b1").CopyFromRecordset (objMyRecordset)
End Sub
如何将A列中的所有页面信息传递到vba中的以下查询字符串? 我正在尝试传递A列中的所有值,而不是range(“ A1”)
objMyCmd.CommandText = "select sum(pageviews) from GA1 where page LIKE '" & Range("A1").Value & "'"
有人可以帮助循环A列中sheet1中的所有页面吗?