我有一系列日期需要转换为 'MM/DD/YYYY 格式(但作为文本)每个月。
我曾经使用这个公式手动转换这些 =TEXT(Cell Ref.,"MM/DD/YYYY")
.见上图。我最近开始使用下面的 VBA 代码来节省我的时间(大约有 18 列,每个月有 200K 行的数据)。
Sub MM_DD_YYYY()
Application.ScreenUpdating = False
Dim rng As Range
Selection.NumberFormat = "0"
For Each rng In Selection
rng.Value = "+text(" & rng.Value & ",""MM/DD/YYYY"")"
Next rng
Selection.TextToColumns DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
如果我选择一列,此代码可以正常工作,但如果我选择多列则失败,因为它有文本到列元素(显然一次只适用于一列)。选择整个范围后是否可以一次运行一列代码而不破坏它?顺便说一句,我尝试了以下文本到列的替代方案:
For Each rng In Selection
SendKeys "{F2}", True
SendKeys "{ENTER}", True
Next
Selection.Value = Selection.FormulaR1C1
For Each rng In Selection
Selection.Value = Selection.Value
Next rng
我非常感谢您的帮助或建议。谢谢。
最佳答案
The output has a apostrophe at the beginning i.e. it's a text. That is why I was using text formula. Selection.NumberFormat = "MM/DD/YYYY" also doesn't work. range of dates are actual dates but output should be a text. – ram singh 12 secs ago
尝试这个。解释见Convert an entire range to uppercase without looping through all the cells .下面的代码使用
INDEX()
和 TEXT()
.Option Explicit
Sub Sample()
Dim rng As Range
Dim sAddr As String
Set rng = Range("A1:C5") '<~~ Change this to relevant range
sAddr = rng.Address
rng = Evaluate("index(""'"" & Text(" & sAddr & ",""MM/DD/YYYY""),)")
End Sub
之前:之后:
编辑
@SiddharthRout Just curious, is it possible to make it to work for more than one range. Example, I have dates in Col A and Col C (Col B has some other data). Current code doesn't work because if I select only Col A and Col C, they are now 2 ranges. Any thoughts? – ram singh 15 mins ago
这是你想要的吗?
Option Explicit
Sub Sample()
Dim rng As Range
Dim ar As Range
Dim sAddr As String
Set rng = Range("A1:A5,C1:C5") '<~~ Sample range
For Each ar In rng.Areas
sAddr = ar.Address
ar = Evaluate("index(""'"" & Text(" & sAddr & ",""MM/DD/YYYY""),)")
Next ar
End Sub
之前:之后:
关于excel - 为一系列列运行相同的 VBA 代码(一次一列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67721795/