Excel VBA尝试将单元格值设置为另一个单元格的日期

时间:2013-01-09 12:20:40

标签: excel vba date-format

我有一个电子表格,我们的组织需要每周为员工提交疾病信息。电子表格在一年中的每个星期都有一个标签,我已经有一个宏可以将员工详细信息从一周复制到下一周。

我正在尝试建立下面的代码,以便接收仍在休病假的工作人员,并将病假的开始日期复制到下一周。代码的工作原理是在循环中将员工编号作为字符串,然后为开始日期创建一个对象。

由于模板的布局和其他信息,我不能简单地将整张纸从一周复制并粘贴到下一周。

REVISED 下面修改后的代码现在将第一个SicknessStart日期复制到NextWeek。但是它仅适用于第一个日期,并且由于某种原因不会从后续行复制信息。日期格式也是以美国格式复制,但我正在调查。

Sub CopyDate

 Dim I As Integer, CopyDate As Boolean
 I = 6
 CopyDate = False

 'Use the Employee Number column (C) to perform the check on the sickness dates
 Do While CurrentWeek.Cells(I, 3) <> ""

'Check if there is a sickness start date in column R
If CurrentWeek.Cells(I, 18) <> "" Then
'Check if they have entered 'Still Away' or left the cell blank in column S
    If CurrentWeek.Cells(I, 19) = "Still Away" Or CurrentWeek.Cells(I, 19) = "" Then

        Dim EmployeeNumber As String
        Dim SicknessStart As String
            EmployeeNumber = Cells(I, 3)
            SicknessStart = Cells(I, 18)

        NextWeek.Select

'Find the employee number string on the following week's tab and enter sickness start date   
        Columns(3).Find(What:=EmployeeNumber, LookIn:=xlValues, LookAt:= _
        xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
        , SearchFormat:=False).Offset(0, 15) = SicknessStart

End If
End If

I = I + 1
Loop
CopySickness = True
End Sub

1 个答案:

答案 0 :(得分:1)

您没有说明如何声明或设置CurrentWeekNextWeek。我将假设它们是全局worksheet变量(顺便说一句,它们应该是传递给此sub的参数),这些变量在别处设置。


然后将所有 cell引用与其中一个进行限定。

        EmployeeNumber = CurrentWeek.Cells(I, 3)
        SicknessStart = CurrentWeek.Cells(I, 18)

此行是您遇到问题的原因(删除它)
为什么?因为第二次通过不合格的EmployeeNumber = Cells(I, 3)等,请参阅表NextWeek

NextWeek.Select

使用Find变量

Range员工编号

Dim rStartDate as Range

' replace your Columns(3).Find(... code with this
Set rStartDate = NextWeek.Columns(3).Find( _
  What:=EmployeeNumber, _
  LookIn:=xlValues, _
  LookAt:=xlWhole, _
  SearchOrder:=xlByRows, _
  SearchDirection:=xlNext, _
  MatchCase:=False, _
  SearchFormat:=False)
If Not rStartDate Is Nothing Then
    rStartDate.Offset(0, 15) = SicknessStart
Else
    ' EmployeeNumber is not found in NextWeek.Column(3)
End If