VBAfunction改变inputDATE

我正在写一个简单的VBA函数来将input(从SSMS复制到Excel)转换成WHERE子句。 像这样:

Imgur /不能直接发布,抱歉/

我已经这样做了,但是我偶然发现了两个要求我提供帮助的问题。

这里有两个问题:

预期 :如果我从以下查询中复制结果,则aqwhere_clause函数应该如图所示生成WHERE子句(在代码中标记)。

with cte ( col1, col2, col3, col4_date ) as ( select N' _1234567890/-+.<>,;:''""][{}\|_!@#$%^& *() ',N'泰Kisk眉头福克斯yumps在Tkhe拉兹狗','',cast('01-01-2015' as date) union ALL select N' _1234567890/-+.<>,;:''""][{}\|_!@#$%^& *() ',N'abcefghijklmnopqrstuvwxyz' ,'',cast('01-05-2016' as date) union ALL select N' _1234567890/-+.<>,;:''""][{}\|_!@#$%^& *() ',N'абвгдеёжзиклмнопрстуфхцчшщъыьэюя','',cast('01-06-2019' as date) ) select * from cte /* this is the part that should be generated ( excluding CRLF )*/ where 1=1 and [col1] in (N' _1234567890/-+.<>,;:''""][{}\|_!@#$%^& *() ', N' _1234567890/-+.<>,;:''""][{}\|_!@#$%^& *() ', N' _1234567890/-+.<>,;:''""][{}\|_!@#$%^& *() ') and [col2] in (N'泰Kisk眉头福克斯yumps在Tkhe拉兹狗', N'abcefghijklmnopqrstuvwxyz', N'абвгдеёжзиклмнопрстуфхцчшщъыьэюя') and [col3] in (N'', N'', N'') and [col4_date] in (N'01-01-2015', N'01-05-2016', N'01-06-2019') /**/ 

实际 :它会生成以下内容:

Imgur /不能直接发布,抱歉/

在文本格式中(我在AND之前添加了\ r \ n以提高可读性):

 where 1=1 and [col1] in (N' _1234567890/-+.<>,;:'""][{}\|_!@#$%^& *() ', N' _1234567890/-+.<>,;:'""][{}\|_!@#$%^& *() ', N' _1234567890/-+.<>,;:'""][{}\|_!@#$%^& *() ') and [col2] in (N'泰Kisk眉头福克斯yumps在Tkhe拉兹狗', N'abcefghijklmnopqrstuvwxyz', N'абвгдеёжзиклмнопрстуфхцчшщъыьэюя') and [col3] in (N'', N'', N'') and [col4_date] in (N'01-Jan-15', N'01-May-16', N'01-Jun-19') 
  1. 它吃[col1]中的两个单引号之一

    可能的解决scheme:replace(cell.value,“'”,“''”)。 有没有更好的办法?

  2. 它将所有date格式转换为“DD-MMM-YY”。 这个问题在世界网上被提及,甚至在这里在stackoverflow 。 但是我所看到的所有解决scheme都是关于强制date模式的。 我不能这样做,因为我的inputdate大部分时间都会有不同的date格式。

    可能的解决scheme:parsing列名或excel单元格格式(如何?)以确定是否是date并强行将列转换为预定模式。 像这样:

    和(N'01-Jan-15',N'01-May-16',N'01-Jun-19')中的CONVERT(datetime,[col4_date],6)

这里是代码:

 Function aqwhere_clause(A_E As Range) As String Dim Arr As Variant Arr = A_E Dim lStrVar As String Dim i As Long Dim j As Long 'Where PREFIX lStrVar = "where 1=1 " For i = LBound(Arr, 2) To UBound(Arr, 2) 'Getting COLUMN_NAME lStrVar = lStrVar + "and " + "[" + CStr(Arr(1, i)) + "]" 'IF Array is more than two rows tall then use IN If UBound(Arr, 1) > 2 Then lStrVar = lStrVar + " in (" For j = LBound(Arr, 1) + 1 To UBound(Arr, 1) 'Getting list of COLUMN_VALUES If CStr(Arr(j, i)) = "NULL" Or CStr(Arr(j, i)) = "Null" Or CStr(Arr(j, i)) = "null" Then lStrVar = lStrVar + "" + "Null" + ", " Else: lStrVar = lStrVar + "N'" + CStr(Arr(j, i)) + "', " End If Next j lStrVar = Left(lStrVar, Len(lStrVar) - 2) + ") " 'IF Array has two rows then use EQUALS ( sanity check on single-dimension row should be passed by user ) 'Getting list of COLUMN_VALUES Else: lStrVar = lStrVar + " = N'" + CStr(Arr(2, i)) + "' " End If Next i aqwhere_clause = lStrVar End Function 

谢谢。