问题描述
希望在 Excel 文件中的 Sheet2 上创建一个新列(“financial_Year”)。在新列中,我们需要使用另一列“Transaction_Date”来计算财政年度,我们如何在 excel 中执行活动。
例如:我们在“Transaction_Date”列中有一个值(12-jan-2020),首先我们需要转换为日期格式,即“2020-01-12”,因为给定的日期在财政年度“ 19-20",因此我们可以在“financial_Year”列中附加值。
每个财政年度都在 4 月到 3 月之间,假设为当前日期 是 06-July-2021,财政年度将是 FY 21-22
输入数据:
col1 Col2 Transaction_Date
India AXN Ltd 12-jan-2020
UK TIL Inc 15-Oct-2021
USA SS Pvt Ltd 06-Mar-2019
Italy Duke Co. 12-Dec-2020
Ger Dell Inc 17-July-2018
预期输出:
col1 Col2 Transaction_Date financial_Year
India AXN Ltd 12-jan-2020 FY 19-20
UK TIL Inc 15-Oct-2021 FY 21-22
USA SS Pvt Ltd 06-Mar-2019 FY 18-19
Italy Duke Co. 12-Dec-2020 FY 20-21
Ger Dell Inc 17-July-2018 FY 18-19
我正在使用的是
="FY" & IF(MONTH(C2)<4,YEAR(C2)-1 & "-" & YEAR(C2),YEAR(C2) & "-" & YEAR(C2)+1)
我们可以使用 VBA 创建相同的内容吗?
我也尝试过使用 VBA
Dim wrkbok As Workbook
Dim wrksht As Worksheet
Dim PRange As Range
Dim LastRow As Long
Dim LastCol As Long
Set wrkbok = Workbooks.Open(strWrkbok)
Set wrksht = wrkbok.Sheets("Sheet2")
On Error Resume Next
LastRow = wrksht.Cells(Rows.Count,1).End(xlUp).Row
LastCol = wrksht.Cells(1,Columns.Count).End(xlToLeft).Column
Set PRange = wrksht.Cells(1,1).Resize(LastRow,LastCol)
Sub InsertColumn()
Columns("C:C").Insert Shift:=xlToRight,copyOrigin:=xlFormatFromLeftOrAbove
Range("C1").Value = "Loc"
End Sub
解决方法
这是使用 VBA 的一种方法:
假设数据从指定工作表上的 A1
开始
还假设列 C
已经存在,并且可以清除
如果不是这种情况,您应该在写入之前插入 col C
Option Explicit
Sub FiscalYear()
Dim WS As Worksheet,rSrc As Range,rRes As Range
Dim vSrc As Variant,vRes As Variant
Dim I As Long
Dim fyStart As Long,fyEnd As Long,tDT As Date
Set WS = ThisWorkbook.Worksheets("Sheet2") 'change worksheet name as appropriate
'read data into vba array for faster processing
With WS
Set rSrc = Range(.Cells(1,3),.Cells(.Rows.Count,3).End(xlUp))
vSrc = rSrc
Set rRes = rSrc.Offset(columnoffset:=1)
End With
'Do the calculation and write results to array for faster processing
ReDim vRes(1 To UBound(vSrc,1),1 To 1)
vRes(1,1) = "Financial_Year"
For I = 2 To UBound(vSrc,1) 'skip header row
'Fiscal year is 1-Apr => 31-Mar
tDT = vSrc(I,1)
If Month(tDT) >= 4 Then
fyStart = Year(tDT) Mod 100
Else
fyStart = Year(tDT) Mod 100 - 1
End If
vRes(I,1) = Format(fyStart,"""FY ""00-") & Format(fyStart + 1,"00")
Next I
'write results to the worksheet
With rRes
.EntireColumn.Clear
.Value = vRes
.EntireColumn.AutoFit
End With
End Sub