【问题标题】:Excel VBA translation date into another formatExcel VBA 将日期翻译成另一种格式
【发布时间】:2019-09-26 02:01:31
【问题描述】:

对 Excel VBA 来说真的很陌生。 一直致力于一项任务,并试图将所有不同的元素拼凑到一个工作宏中。

这是我的目标

正如您在图片中看到的, 有一份当月报告休假的 ID 和姓名列表。

我想翻译成以下格式 开始日期/结束日期/所用小时数

1 尝试使用代码捕获开始日期,但未能恢复循环以捕获结束日期。

Sub FindMatchingValue()
    Dim i As Integer, intValueToFind As Integer
    intValueToFind = 8
    For i = 1 To 500    ' Revise the 500 to include all of your values
        If Cells(2, i).Value = intValueToFind Then
            MsgBox ("Found value on row " & i)
            Cells(2, 35).Value = Cells(1, i) 'copy the start date to same row column 35
            Exit Sub
        End If
    Next i

    ' This MsgBox will only show if the loop completes with no success
    MsgBox ("Value not found in the range!")
End Sub

2 结束日期将是连续休假的员工的最后一天。

非常感谢我们社区的帮助。

【问题讨论】:

  • 不会恢复,因为有 ExitSub。 CaptureEndDate 也未与我们共享。为什么要求中有连续天数?此外,开始日期可能是下午的 4 小时(而不是 intValueToFind 的 8 小时),然后是一整天。一个人的多次离开数据未显示在数据中,也未在代码中处理。很难想象一张有 250 列的表格——一年中的每个工作日一个,然后乘以 2 两年。数据库的设计需要工作。
  • @excelabc19 你能用图片显示结果吗?
  • @donPablo 您好,感谢您为我指出这一点。因为我想把请假请求分成小块,而不是一天一个条目,我相信这会有点混乱。我知道时间可能会有所不同,并且仅使用 8 作为测试,正在考虑将其设为 >=0。
  • @PaichengWu Hi Paicheng 感谢您的回复,我现在更新了图片,请看一下。

标签: excel vba date


【解决方案1】:

以下代码将为您返回第一个 ID(第 2 行)的第一组连续休假,其中包含开始日期、结束日期和所用小时数:

Sub FindMatchingValue()
    Dim i As Integer, intValueToFind As Integer, Found As Boolean, HoursTaken As Single
    intValueToFind = 8
    For i = 1 To 34    'Considering 34 is the max date column
        If Found Then
            If Cells(2, i).Value = "" Then
                MsgBox ("Last consecutive column " & i - 1)
                Cells(2, 36).Value = Cells(1, i - 1) 'copy the end date to same row column 36
                Cells(2, 37).Value = HoursTaken 'Hours taken to same row column 37
                Found = False
                Exit Sub 'Skip after first set of leave
            Else
                HoursTaken = HoursTaken + Cells(2, i)
            End If
        ElseIf Cells(2, i).Value = intValueToFind Then
            MsgBox ("Found value on column " & i)
            Cells(2, 35).Value = Cells(1, i) 'copy the start date to same row column 35
            Found = True
            HoursTaken = Cells(2, i)
        End If
    Next i

    'This MsgBox will only show if the loop completes with no success
    MsgBox ("Value not found in the range!")
End Sub

您必须更多地考虑如何捕获同一个人的下一组休假并为整个数据行运行它。希望这将有助于解决您的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-27
    相关资源
    最近更新 更多