日期值更改

时间:2017-07-04 11:29:30

标签: excel vba date

我尝试根据大量电子表格创建数据库。我的目标是通过大量的电子表格将所需信息提取到一个格式良好的表格中。我刚刚开始,所以我写了一些函数来提取我需要的东西。我将它们存储在变量中,然后将它们放入表中。

我编写的函数在一个字符串范围内搜索字符串,并在其旁边的单元格中提取信息。它似乎对字符串很好。

有人可以解释日期发生了什么吗?我希望它以英国格式输出日期dd / mm / yyyy。目前,01/06/2018到期日期为英国格式。如果我调试它并放入打印件,它将以英国格式出现。如果我检查它所存储的单元格的格式,并且它返回的单元格都是英国格式。然而它出现在06/01/2018。

如果可能,可以在答案中包含对正在发生的事情的解释,而不是"只需将代码更改为此"解决方案,以便我可以了解它是如何解释它的?

任何帮助都将不胜感激。

这是代码

Private Sub Main()

'Turn off screen updating
Application.ScreenUpdating = False

'Define the variables
Dim Coverholder As String
Dim SearchRange As Range

'set the range to search
Set SearchRange = Sheets("2017 Property").Range("A1:AZ100")

'testing
Range("A1").Value = GetNextTo(SearchRange, "*Expiry*")

Debug.Print GetNextTo(SearchRange, "*Expiry*")

'Reset the position of the selection
Range("A1").Select

'Turn on the screen updating
Application.ScreenUpdating = True

End Sub

'Function to return the value one cell to the right of a search value
Private Function GetNextTo(SearchRange As Range, FindString As String) As String

    'Define variables
    Dim Rng As Range

    'Clean the string
    If Trim(FindString) <> "" Then
        'use the search range
        With SearchRange
            Set Rng = .Find(What:=FindString, _
                            After:=.Cells(.Cells.Count), _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, _
                            MatchCase:=False)
            'If value found
            If Not Rng Is Nothing Then

                Application.Goto Rng.Offset(0, 1)

            'If value not found
            Else

                MsgBox "Nothing found"

            End If
        End With
    End If

    GetNextTo = ActiveCell.Value

End Function

1 个答案:

答案 0 :(得分:0)

这就是发生的事情(据我所知):

excel中的日期显示为(例如)dd.mm.jjjj,但不以这种方式存储。您可以通过在单元格中打印日期来测试:

创建一个新的wb,在第一个单元格中输入12.11.1985,然后运行:

Sub test()
 'returns value of cell properly formated (but not always as displayed in the cell)
 Debug.Print Cells(1, 1).Value
 'returns the actual value of the cell
 Debug.Print Cells(1, 1).Value2
End Sub

.Value2将返回31363,这是单元格中的实际值。此值将以不同方式解释,具体取决于各种设置以及您使用它提取的功能。

至于解决方案,请参阅@Doomeniks评论。

编辑:Doomenik将一些优秀的答案联系起来,远比这个答案更深入。