简体   繁体   English

使用 VBA TextToColumns 将文本更改为最新

[英]Change Text to Date with VBA TextToColumns

Edit: VBA code now is working.编辑:VBA 代码现在可以使用。 Was just and.currentregion that messed it up for me只是 and.currentregion 把我搞砸了

I have an issue, that is hopefully just some silly mistake from myside.我有一个问题,希望这只是我这边的一些愚蠢错误。 I have a dataset that I get at least once a day with the dates not recognised as date, but as normal text.我有一个数据集,每天至少获取一次,其中的日期未被识别为日期,而是被识别为普通文本。 I would like to have this column changed to date with a VBA macro.我想用 VBA 宏将此列更改为最新。 The code I have written now, just gives me an error message, and I can not figure out what is wrong.我现在写的代码,只是给我一个错误信息,我不知道哪里出了问题。

This is how the file looks, I could not figure out how to attach the file...这是文件的样子,我不知道如何附加文件...

在此处输入图像描述

And here is my code这是我的代码

Sub Test()

Dim rg As Range
Set rg = Range("B2:B4")
rg.TextToColumns Destination:=Range("B2:B5"), ConsecutiveDelimiter:=True, DataType:=xlDelimited, Space:=True, FieldInfo:=Array(Array(1, 5))

End Sub

Any suggestion what might be wrong with the code or how I can make it work?任何建议代码可能有什么问题或者我如何才能让它工作? The date format is YMD when I do this in the Text to Columns in excel itself.当我在 excel 本身的文本到列中执行此操作时,日期格式为 YMD。 This is a part of a bigger VBA, so it would be much easier to do it as a VBA than to do it manually every time I need it.这是一个更大的 VBA 的一部分,所以将它作为 VBA 来做比每次我需要它时手动做要容易得多。

In Excel I would use the following, assuming ERIKA's date is in B2:在 Excel 中,假设 ERIKA 的日期在 B2 中,我将使用以下内容:

=DATE(LEFT(B2,4),MID(B2,5,2),RIGHT(B2,2))

In VBA, in a function, I would use:在 VBA 中,在 function 中,我会使用:

Function TextToDate(txt As String) As Date
TextToDate = DateSerial(Left(txt, 4), Mid(txt, 5, 2), Right(txt, 2))
End Function

I suggest to load all data to an array and then run the "migration".我建议将所有数据加载到一个数组中,然后运行“迁移”。 Using an array to manipulate data is much faster then working on cells directly.使用数组来操作数据比直接处理单元格要快得多。

Alternatively you can use a formula as well.或者,您也可以使用公式。


Option Explicit

Public Sub migrateDate()
Dim ws As Worksheet: Set ws = ActiveSheet   'adjust to your needs
Dim rgDates As Range
Set rgDates = ws.Range("B2:B5")  'adjust to your needs, use explicit .Range referencing the worksheet you want to work on - not an implicit Range!!!

Dim arrDates As Variant
arrDates = rgDates.Value

Dim i As Long
Dim strDate As String, year As Long, month As Long, day As Long

For i = 1 To UBound(arrDates, 1)
    strDate = arrDates(i, 1)
    If LenB(strDate) > 0 Then
        If IsNumeric(strDate) And Len(strDate) = 8 Then
            year = Left(strDate, 4)
            month = Mid(strDate, 5, 2)
            day = Right(strDate, 2)
        End If
        arrDates(i, 1) = DateSerial(year, month, day)
    End If
Next

rgDates.Value = arrDates

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM