excel vba读取日期为dd / mm / yyyy

问题描述 投票:0回答:2

我有一个Excel VBA代码,可以按月将外部工作簿中的数据检索到工作表中。

我想找回11月,但我似乎无法输入日期#30/11/2017#。日期将自动更改为#11/30/2017#。

日期必须是dd / mm / yyyy,因为这是外部工作簿中日期的格式。

Sub zz()
Dim arr, c, b(), n&
Application.ScreenUpdating = False
Worksheets("Sheet2").Range("A6").AutoFilter
Workbooks.Open "C:\Users\sophia.tan\Desktop\excel masterplan\External 
workbook.xlsx", 0, 1
arr = Sheets("MaximMainTable").UsedRange
ActiveWorkbook.Close 0
c = Array(0, 2, 12, 13, 6, 7, 10, 1, 8, 9, 15, 16, 18, 19, 14, 27, 24, 25, 
26, 3, 4, 36)
d = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 
20, 21, 23)
ReDim b(1 To UBound(arr), 1 To 23)
Selection.NumberFormat = "dd/mm/yyyy"
For i = 2 To UBound(arr)
If arr(i, 12) >= (#1/11/2017#) And arr(i, 12) <= Format(#11/30/2017#) Then
    n = n + 1
    For j = 1 To UBound(c)
        b(n, d(j)) = arr(i, c(j))
    Next
End If
Next

Dim startRow As Long, lastRow2 As Long
startRow = 6
lastRow = Cells(Cells.Rows.Count, 1).End(xlUp).Row

For i = startRow To lastRow

If Range("A" & i) Like "MX*" Then

    If Range("J" & i) Like "*Rib*" Then
         Range("M" & i) = "Rib"

    ElseIf Range("J" & i) Like "*Spandex*Pique*" Then
         Range("M" & i) = "Spandex Pique"

    ElseIf ("J" & i) Like "*Pique*" Then
         Range("M" & i) = "Pique"

    ElseIf ("J" & i) Like "*Spandex*Jersey*" Then
         Range("M" & i) = "Spandex Jersey"

    ElseIf Range("J" & i) Like "*Jersey*" Then
         Range("M" & i) = "Jersey"

    ElseIf ("J" & i) Like "*Interlock*" Then
         Range("M" & i) = "Interlock"

    ElseIf ("J" & i) Like "*French*Terry*" Then
         Range("M" & i) = "Fleece"

    ElseIf ("J" & i) Like "*Fleece*" Then
         Range("M" & i) = "Fleece"

    Else


     Range("M" & i) = "Collar & Cuff"


    End If
    End If

 Next
 With Worksheets("Sheet2")
 .Range("A6:T" & Rows.Count).CurrentRegion.AutoFilter field:=1, Criteria1:="
 <>OFM"
 .Range("A6:T" & 
 Rows.Count).CurrentRegion.SpecialCells(xlCellTypeVisible).AutoFilter 
 field:=13, Criteria1:="<>Collar & Cuff"
 .Range("A6:T" & Rows.Count).CurrentRegion.Offset(1, 
 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
 .Range("A6").Resize(n, 23) = b
 .Range("A5").CurrentRegion.Sort key1:=Range("G5"), order1:=xlAscending, 
  Header:=xlYes


 End With



 Application.ScreenUpdating = 1

 End Sub
excel vba excel-vba date
2个回答
0
投票

当您直接使用#date#表示法时,VBA期望它采用mm/DD/yyyy格式。


0
投票

要测试工作表上的日期是否在2017年11月:

If arr(i, 12) >= #11/1/2017# And arr(i, 12) <= #11/30/2017# Then
   'do whatever
End If

只要Excel中的日期是“实际日期”,工作表单元格中日期的格式就无关紧要了。

如果Excel中的日期是文本,则需要在进行比较之前将它们转换为实际日期。无论您是在工作表上还是在代码中执行此操作,都无关紧要。

对于代码中的日期文字,您可以替换解析为VBA日期数据类型的其他变量。请注意,如果转换String,则String必须采用明确的格式(只能以单向方式解释)。

DateSerial(2017, 11, 1)
CDate("2017-11-01")
CDate("1 Nov 2017")
© www.soinside.com 2019 - 2024. All rights reserved.