Skip to content

Instantly share code, notes, and snippets.

@taojy123
Created January 20, 2015 01:32
Show Gist options
  • Save taojy123/b8ed2f406158d72dab77 to your computer and use it in GitHub Desktop.
Save taojy123/b8ed2f406158d72dab77 to your computer and use it in GitHub Desktop.
excel 宏 自动分割日期
Attribute VB_Name = "模块1"
Sub 自动分割日期()
'先把15天的数据清空
For i = 1 To 15
'选择每一张表
Sheets(CStr(i)).Select
'全选 清空
Cells.Select
Selection.Delete
Next i
'循环处理主表的每一行,这里可以用for循环设定一个比较大的上限,也可以用while循环
For i = 2 To 200
'每处理一行前先确保选择了 总表1
Sheets("总表1").Select
'获取这一行第一个格子的值,即为当天日期
today = CStr(Cells(i, 1).Value)
'将日期字符串通过/符号拆分成三个部分
ds = Split(today, "/")
'如果拆分出来不是三个部分,说明这一行开始就没有数据了,可以直接退出循环,结束完成
If UBound(ds) <> 2 Then
Exit For
End If
'将主表中的这一整行复制
Rows(i & ":" & i).Select
Selection.Copy
'd是前面拆分日期的第三个拆分项,即为日数
d = ds(2)
'根据日数选择对应的日表
Sheets(d).Select
'在日表中从第二行开始判断,哪一行是空的就在哪一行插入新数据
For j = 2 To 100
If Cells(j, 1).Value = "" Then
'选择对应行号
Rows(j & ":" & j).Select
'粘贴前面从主表复制的那一行数据
ActiveSheet.Paste
'粘贴一次后就可以退出这个小循环了
Exit For
End If
Next j
'下面再做一些补充工作,如果第一行没有表头,就从主表中复制过来粘贴到第一行
If Cells(1, 1).Value = "" Then
'选项主表第一行
Sheets("总表1").Select
Rows("1:1").Select
'复制
Selection.Copy
'选择日表第一行
Sheets(d).Select
Rows("1:1").Select
'粘贴
ActiveSheet.Paste
End If
'这样就完成了对主表一行数据的处理,依次处理下面每一行
Next i
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment