gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:17:28 26 4
gpt4 key购买 nike

我有一系列日期需要转换为 'MM/DD/YYYY 格式(但作为文本)每个月。
Range
我曾经使用这个公式手动转换这些 =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
如果我选择一列,此代码可以正常工作,但如果我选择多列则失败,因为它有文本到列元素(显然一次只适用于一列)。选择整个范围后是否可以一次运行一列代码而不破坏它?
顺便说一句,我尝试了以下文本到列的替代方案:
  • 模拟 F2+Enter。这有效,但需要很多时间。
  • 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
    之前:
    enter image description here
    之后:
    enter image description here
    编辑

    @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
    之前:
    enter image description here
    之后:
    enter image description here

    关于excel - 为一系列列运行相同的 VBA 代码(一次一列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67721795/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com