坚持多种条件并比较字符串

时间:2016-07-18 08:24:24

标签: excel vba excel-vba

我有一些代码可以从一堆excel文件中创建一个汇总表。代码复制并使用xlPasteSpecialOperationAdd将所选范围从每个文件粘贴到临时工作表。

摘要表有2个输入单元格,用于确定条件。第一个单元格包含可以是[ALL,0,1,2,3,4,5]的状态。第二个字段是yyyy / mm / dd格式的日期。

建议填充第一个单元格,第二个单元格是可选的。如果第二个单元格为空,则日期无关紧要。

我认为比较日期或可能不正确的条件我有些困难。为了比较日期,我使用了两个函数:LIKE和StrComp,但它们都没有工作,或者可能是因为条件不正确。 请帮我解决此代码的修复方法:

将输入单元格文本设置为字符串变量(2016.07 = 7个带点的字符):

'Get input date as string
  AstrDate = OutputWs.Range("P5").Text
'Set the date to year and month format
  AstrDateChars = Left$(strDate, 7)

确定单元格是否为空白:

'if the input range is blank then rangeBlank is true
  If IsEmpty(OutputWs.Range("P5")) = True Then
    rangeBlank = True
  Else
    rangeBlank = False
  End If


'Get the output date to compare with
BstrDate = oNewBook.Sheets(1).Range("R22").Text

获取输出值:

'Set the compared date to year and month format
BstrDateChars = Left$(strDate, 7)

与StrComp函数进行比较并将值存储到布尔变量中:

'compare date strings
'compareResult = StrComp(AstrDateChars, BstrDateChars, vbBinaryCompare)

与Like函数比较:

compareResult = AstrDateChars Like BstrDateChars

条件:

'Which IL status you want to copy?
If inputValue = "ALL" And rangeBlank = True Then                                                   'Search for all IL status
    oNewBook.Worksheets(1).Range("G25:N28").Copy
    tempWS.Range("G25:N28").PasteSpecial Paste:=xlPasteAll, operation:=xlPasteSpecialOperationAdd
    oNewBook.Close
ElseIf inputValue = outputValue And rangeBlank = True Then                                         'Search for only the selected IL status
    oNewBook.Worksheets(1).Range("G25:N28").Copy
    tempWS.Range("G25:N28").PasteSpecial Paste:=xlPasteAll, operation:=xlPasteSpecialOperationAdd
    oNewBook.Close


ElseIf inputValue = "ALL" And rangeBlank = False And compareResult = True Then                            'Searcg ALL IL status and date
    oNewBook.Worksheets(1).Range("G25:N28").Copy
    tempWS.Range("G25:N28").PasteSpecial Paste:=xlPasteAll, operation:=xlPasteSpecialOperationAdd
    oNewBook.Close
ElseIf inputValue = "ALL" And rangeBlank = False And compareResult = False Then                           'Searcg ALL IL status and date, If date does not match, then closes the document
    oNewBook.Close


ElseIf inputValue = outputValue And rangeBlank = False And compareResult = True Then                      'Search for the selected IL0-IL5 and date
    oNewBook.Worksheets(1).Range("G25:N28").Copy
    tempWS.Range("G25:N28").PasteSpecial Paste:=xlPasteAll, operation:=xlPasteSpecialOperationAdd
    oNewBook.Close
ElseIf inputValue = outputValue And rangeBlank = False And compareResult = False Then                     'Search for the selected IL0-IL5 and date, if date does not match, then closes the document
    oNewBook.Close
End If

1 个答案:

答案 0 :(得分:0)

尝试使用StrComp:

compareResult = (StrComp(AstrDateChars, BstrDateChars, vbBinaryCompare)=0)