[英]strSQL between date range excel VBA
I am trying to run an strSQL within Excel VBA between two date ranges.我正在尝试在两个日期范围之间的 Excel VBA 内运行 strSQL。
See below part of my code relevant to this:请参阅以下与此相关的代码部分:
Dim DateMin As String
Dim DateMax As String
DateMin = Format$(Sheets("Setup").Range("c5").Value, "mm/dd/yyyy")
DateMax = Format$(Sheets("Setup").Range("c6").Value, "mm/dd/yyyy")
strSQL = "SELECT [COSTCENTRE_CODE],[PROJECT_CODE],[HOME_VALUE],[CT_DEADLINE] FROM [AA_CST_CENTRE_TRANSACTION_SIMPLE_VIEW] where [CT_DEADLINE] between #" & DateMin & "# AND #" & DateMax & "#"
When I run this I get an "incorrect syntax nea '#'" error.当我运行它时,我得到一个“不正确的语法 nea '#'”错误。 The format of cells C5 + C6 are in the same mm/dd/yyyy format - am using the American date format as believe SQL only uses American dates?单元格 C5 + C6 的格式与 mm/dd/yyyy 格式相同 - 我使用美国日期格式,因为相信 SQL 仅使用美国日期? I have tried adjusting the dates but no luck.我试过调整日期,但没有运气。
When I run "debug.print strsql" I get the below:当我运行“debug.print strsql”时,我得到以下信息:
SELECT [COSTCENTRE_CODE],[PROJECT_CODE],[HOME_VALUE],[CT_DEADLINE] FROM [AA_CST_CENTRE_TRANSACTION_SIMPLE_VIEW] where [CT_DEADLINE] between #02/01/2020# AND #03/31/2020#
I have tried removing the #
around the dates and I no longer get the error, however no data shows at all - there is definitely data there for these dates.我已经尝试删除日期周围的#
并且我不再收到错误,但是根本没有数据显示 - 这些日期肯定有数据。
Anyone have any ideas as believe this is an SQL issue rather than an Excel VBA issue?任何人都有任何想法,认为这是 SQL 问题而不是 Excel VBA 问题?
Does running this SQL work?运行这个 SQL 有效吗? SELECT [COSTCENTRE_CODE],[PROJECT_CODE],[HOME_VALUE],[CT_DEADLINE] FROM [AA_CST_CENTRE_TRANSACTION_SIMPLE_VIEW]
just to make sure the issue is in the date part and not before. SELECT [COSTCENTRE_CODE],[PROJECT_CODE],[HOME_VALUE],[CT_DEADLINE] FROM [AA_CST_CENTRE_TRANSACTION_SIMPLE_VIEW]
只是为了确保问题出在日期部分而不是之前。 If this is not running then the issue is in this part and not in the date part.如果这没有运行,那么问题出在这部分而不是日期部分。
And I believe SQL is using YYYY-MM-DD hh:mm:ss.sss
as date format.而且我相信 SQL 使用YYYY-MM-DD hh:mm:ss.sss
作为日期格式。 Check that out if you have done the first suggested test and this query runs.检查您是否已完成第一个建议的测试并且此查询运行。
And as far as I know only Access accepts #
but in SQL-Server you would neet to use '
instead (which should also work for Access).据我所知,只有 Access 接受#
但在 SQL-Server 中,您需要使用'
代替(这也适用于 Access)。
Also note that另请注意
BETWEEN '02/01/2020' AND '03/31/2020'
is actually:实际上是:
BETWEEN '02/01/2020 00:00:00.000' AND '03/31/2020 00:00:00.000'
So notice that you are missing anything that happened after 12am on 03/31/2020
.因此请注意,您错过了 2020 年 3 月 31 日凌晨 12 点之后发生的任何03/31/2020
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.