==标题==
计算文本格式“yyyymm”或“yyyymmdd”计算年、月、日差额的自定义函数 |
==正文==
【问题】
我们在Excel中输入日期,有两种方式,
1.单元格是日期格式的输入。系统会有自动识别
2.有许多人习惯是用文本格式输入方式,如下图
在Excel的单元格中常要填写这样子的年月或年月日的数据
为了完成以上的工作,设计一个自定义函数
先说一下Excel和VB.net的一点不同
1.在Excel中,年月日用“yyyymmdd”表示,
2.在VB.net中年月日用“yyyyMMdd”表示
【函数】
VSTO插件可以更好的使用VB.net的编程方式.
一、自定义函数,代码如下
'函数功能:计算形如[yyyyMM]与[yyyyMMdd]格式.开始与终止的年、月、日差额
Public Function StartAndEndGetYMD(startDateStr As String, endDateStr As String, yMd As String) As Double
Dim startDate As DateTime
Dim endDate As DateTime
Dim temp As Double
Try
If startDateStr.Length = 6 Then startDateStr += "01"
If endDateStr.Length = 6 Then endDateStr += "01"
startDate = DateTime.ParseExact(startDateStr, "yyyyMMdd", Nothing)
endDate = DateTime.ParseExact(endDateStr, "yyyyMMdd", Nothing)
Dim tM As Integer = DateDiff(DateInterval.Month, startDate, endDate)
Select Case yMd
Case "y"
temp = Math.Round(tM / 12, 2)
Case "M"
temp = Double.Parse(tM)
Case "d"
temp = DateDiff(DateInterval.Day, startDate, endDate)
End Select
Return temp
Catch ex As Exception
Return 0.0
End Try
End Function
2.函数使用方法
with Activesheet
for i=2 to 6
.cells(i,3).value=StartAndEndGetYMD(.cells(i,1).text,.cells(i,2).text,"y")'计算年数差额
.cells(i,6).value=StartAndEndGetYMD(.cells(i,4).text,.cells(i,5).text,"M")'计算月数差额
next
end with
==The end==
==合集==
====若有用,请转发免费学习====
关注看更多文章