运行 一系列列的相同 VBA 代码(一次一列)

Running same VBA code for a range of columns (one column at a time)

我有一个日期范围,我需要每月将其转换为 'MM/DD/YYYY 格式(但为文本格式)。

我曾经使用这个公式 =TEXT(Cell Ref.,"MM/DD/YYYY") 手动转换这些。见上图。我最近开始使用下面的 VBA 代码来节省我的时间(每个月大约有 18 列 20 万行数据)。

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

如果我 select 一列,此代码工作正常,但如果我 select 多列,则失败,因为它有文本到列元素(显然一次只适用于一列)。是否可以 运行 在 select 对整个范围进行编码而不破坏它之后一次编码一列?

顺便说一句,我尝试了以下文本到列的替代方法:

  1. 正在模拟 F2+Enter。这可行,但需要很多时间。
For Each rng In Selection
    SendKeys "{F2}", True
    SendKeys "{ENTER}", True
Next
  1. 由于某种原因不起作用。
Selection.Value = Selection.FormulaR1C1
  1. 由于某种原因不起作用。
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

之前:

之后: