Как уже упоминалось в комментариях, использование SQL с ADODB, вероятно, лучше, чем использование сводных таблиц. Я бы также рекомендовал отделить ваши данные (Sheet1) от уровня презентации (Excel). Например. хранить ваши данные в фактической базе данных, такой как Access, SQL Server и т. д.
Однако, поскольку вы ищете пробел, я подумал, что мог бы дать вам подход, который мог бы удовлетворить потребность временно. Код комментируется, но не стесняйтесь задавать вопросы. Вам нужно будет добавить ссылку на Microsoft Active X Data Object 2.8 or greater
, чтобы это работало. Как добавить ссылку?
Подход раннего связывания
Option Explicit
Public Sub DisplayView(StartDate As Date, EndDate As Date)
'Add a reference to Microsoft Active X Data Object 2.8 or greater
Dim dbConnection As ADODB.Connection
Dim dbRecordset As ADODB.Recordset
Dim dbCommand As ADODB.Command
Dim OutputSheet As Excel.Worksheet
Dim dbField As Variant
Dim fieldCounter As Long
Set dbConnection = New ADODB.Connection
Set dbRecordset = New ADODB.Recordset
Set dbCommand = New ADODB.Command
Set OutputSheet = ThisWorkbook.Worksheets("Sheet2")
'Do a quick check to determine the correct connection string
'if one of these don't work, have a look here --> https://www.connectionstrings.com/excel/
If Left$(ThisWorkbook.FullName, 4) = "xlsm" Then
dbConnection.connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
ThisWorkbook.FullName & ";Extended Properties='Excel 12.0 Macro;HDR=YES';"
Else
dbConnection.connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
ThisWorkbook.FullName & ";Extended Properties='Excel 12.0;HDR=YES';"
End If
'Open the connection and parameterize the query
dbConnection.Open
With dbCommand
.ActiveConnection = dbConnection
.CommandType = adCmdText
'A in B in the text below are the field names in your Sheet 1
'I wasn't sure what the names of the fields are so I named them as they appeared
'That being Column A is called A, Column B is called B etc
.CommandText = "Select * from [Sheet1$] where B in ('A','X') and A >= @StartDate and A < @EndDate"
.Parameters.Append .CreateParameter("@StartDate", adDate, adParamInput, , StartDate)
.Parameters.Append .CreateParameter("@EndDate", adDate, adParamInput, , EndDate)
Set dbRecordset = .Execute
End With
'Clear the Output Sheet
OutputSheet.Cells.Clear
'Add Headers to output
For Each dbField In dbRecordset.Fields
fieldCounter = fieldCounter + 1
OutputSheet.Cells(1, fieldCounter).Value2 = dbField.Name
Next
'Dump the found records
OutputSheet.Range("A2").CopyFromRecordset dbRecordset
If dbConnection.State = adStateOpen Then dbConnection.Close
End Sub
'Run from here
Public Sub ExampleRunner()
'Supply the dates you want to filter for
DisplayView #1/1/2019#, #1/20/2019#
End Sub
По запросу, здесь Позднее связывание Подход , который не требует явной ссылки на Microsoft Active X Data Object
.
Option Explicit
Private Const adCmdText As Long = 1
Private Const adDate As Long = 7
Private Const adParamInput As Long = 1
Public Sub DisplayView(StartDate As Date, EndDate As Date)
'Add a reference to Microsoft Active X Data Object 2.8 or greater
Dim dbField As Variant
Dim fieldCounter As Long
Dim dbConnection As Object
Dim dbRecordset As Object
Dim dbCommand As Object
Dim OutputSheet As Excel.Worksheet
Set dbConnection = CreateObject("ADODB.Connection")
Set dbRecordset = CreateObject("ADODB.Recordset")
Set dbCommand = CreateObject("ADODB.Command")
Set OutputSheet = ThisWorkbook.Worksheets("Sheet2")
'Do a quick check to determine the correct connection string
'if one of these don't work, have a look here --> https://www.connectionstrings.com/excel/
If Left$(ThisWorkbook.FullName, 4) = "xlsm" Then
dbConnection.connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
ThisWorkbook.FullName & ";Extended Properties='Excel 12.0 Macro;HDR=YES';"
Else
dbConnection.connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
ThisWorkbook.FullName & ";Extended Properties='Excel 12.0;HDR=YES';"
End If
'Open the connection and parameterize the query
dbConnection.Open
With dbCommand
.ActiveConnection = dbConnection
.CommandType = adCmdText
'A in B in the text below are the field names in your Sheet 1
'I wasn't sure what the names of the fields are so I named them as they appeared
'That being Column A is called A, Column B is called B etc
.CommandText = "Select * from [Sheet1$] where B in ('A','X') and A >= @StartDate and A < @EndDate"
.Parameters.Append .CreateParameter("@StartDate", adDate, adParamInput, , StartDate)
.Parameters.Append .CreateParameter("@EndDate", adDate, adParamInput, , EndDate)
Set dbRecordset = .Execute
End With
'Clear the Output Sheet
OutputSheet.Cells.Clear
'Add Headers to output
For Each dbField In dbRecordset.Fields
fieldCounter = fieldCounter + 1
OutputSheet.Cells(1, fieldCounter).Value2 = dbField.Name
Next
'Dump the found records
OutputSheet.Range("A2").CopyFromRecordset dbRecordset
If dbConnection.State = adStateOpen Then dbConnection.Close
End Sub
'Run from here
Public Sub ExampleRunner()
'Supply the dates you want to filter for
DisplayView #1/1/2019#, #1/20/2019#
End Sub
(источник: amazon.com)
SQL Вкратце O'Reilly and Associates. Это покрывает все 5 главных Диалектов SQL, различия между ними, и делает это для каждой перечисленной функции/функции. (ANSI SQL99, Oracle, MySql, Пост-ГРЭС и SQL Server).
Номер один способ изучить различия должен работать в различных базах данных.
SQL Server, Oracle и MySql все предложение свободные (специальные) выпуски. Кроме того, если Вы хотите повыситься немного, можно получить версию разработчика SQL Server приблизительно за 50$.
Oracle: http://www.oracle.com/technology/products/database/xe/index.html
SQL Server http://www.microsoft.com/express/sql/default.aspx
MySQL http://dev.mysql.com/downloads/
Простые вещи сделать:
PostgreSQL более усовершенствованная и более совместимая ANSI SQL база данных с открытым исходным кодом в мире
Различное соответствие ANSI SQL RDBMS: http://troels.arvin.dk/db/rdbms/