【发布时间】:2018-07-21 21:32:20
【问题描述】:
我基本上想从相应的列中提取年、月和日,并用它们用VBA创建一个excel格式的日期列。
使用屏幕截图,它首先应该是这样的: Excel Spreadsheet with Year Column and Date Column.
然而,最终应该删除年份列,只保留日期列(撇开描述)并包含 excel 格式的日期。 Excel Spreadsheet with Date Column only
现在,可能有更简单的方法来完成这项任务,但我采取的方法是:
- 在日期列的右侧插入两个新列
- 选择日期列并使用Text to Columns功能将月份移动到右侧新创建的列
- 将新创建的第二个空白列格式化为日期类别
- 在此空白列的单元格中插入日期函数,然后将其自动填充到下面的单元格中。更准确地说,这个日期函数是:=DATE(A2,MONTH(1&C2),B2)
- 复制此新日期列并将其粘贴回作为值,仅供以后排序之用。
- 删除所有其他无用的列(年、月、日)
虽然这在 excel 界面上是可行的,但我想用 VBA 来完成这个任务,所以我已经写了很多代码。不幸的是,作为 VBA 的新手,我目前被困在最后日期列中应用公式。
在您查看我的代码之前,我还想指出,我提示用户选择 Description 列作为参考列,因为并非总是如此年份列是第一列,或者日期列是第二列。然而,绝对可以肯定的是,在描述列的左侧,分别有日期和年份列。
最后,如果有人还通过仅允许将公式应用于包含年份或日期的第一行和最后一行(同样的事情)来改进我的 VBA 代码,我将不胜感激。
提前感谢大家。
下面是我的代码
Sub Macro1()
'Set variables
Dim DescRng As Range
Dim DayRng As Range
Dim MonthRng As Range
Dim YearRng As Range
Dim DateRng As Variant
'Obtain reference column with prompt
Set DescRng = Application.InputBox("Select Description Column", "Obtain Object Range", Type:=8)
'Create new columns from reference column
Columns(DescRng.Column).Insert Shift:=x1ToLeft
Columns(DescRng.Column).Insert Shift:=x1ToLeft
'Assign variables to columns
Set DateRng = DescRng.Offset(rowOffset:=0, columnOffset:=-1)
Set MonthRng = DescRng.Offset(rowOffset:=0, columnOffset:=-2)
Set DayRng = DescRng.Offset(rowOffset:=0, columnOffset:=-3)
Set YearRng = DescRng.Offset(rowOffset:=0, columnOffset:=-4)
'Seperate the days from the months with TextToColumns
Columns(DayRng.Column).TextToColumns Destination:=DayRng, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
'Format the DateRng column for later sorting use
Columns(DateRng.Column).NumberFormat = "yyyy-mm-dd"
'Apply Formula to DateRng Column
'Copy Formula in DateRng and paste into the same column as values
Columns(DateRng.Column).Copy
Columns(DateRng.Column).PasteSpecial Paste:=xlPasteValues, SkipBlanks _
:=False, Transpose:=False
'Delete the other Columns (YearRng, MonthRng, DayRng)
YearRng.Delete
DayRng.Delete
MonthRng.Delete
End Sub
编辑:感谢您的回答带来的洞察力。与我未完成的任务不同,您用简短的代码完成了一项简单的任务。从我的第一篇文章中学到了很多。谢谢
【问题讨论】:
-
Col B(在初始照片中)的格式是文本还是日期?您可以通过将单元格格式化为数字来进行检查。如果它保持不变,它是文本。如果是数字,则将日期转换为其对应的序列号。 -
你的问题到底是什么?
-
我想用 VBA 从图 1 转到图 2
-
初始照片中的 B 列根本没有格式化*。我假设它是一般的。
-
格式化为数字时它不会改变这一事实明确地告诉我们,该值是一个字符串,而不是已格式化为 dd mmm 的真实日期。