编辑: VBA代码现在可以工作了。就是just和.currentregion把我搞砸了
我有一个问题,希望这只是我的一些愚蠢的错误。我有一个数据集,我每天至少获得一次,日期不被识别为日期,而是普通文本。我希望使用VBA宏将此列更改为最新列。我现在编写的代码只是给了我一条错误消息,我不知道哪里出了错。
这是文件的样子,我不知道如何附加文件...
下面是我的代码
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
有什么建议,代码可能出了什么问题,或者我如何才能让它工作?当我在excel本身的“文本到列”中执行此操作时,日期格式为YMD。这是一个更大的VBA的一部分,所以作为一个VBA来做要比每次我需要它时手动做要容易得多。
发布于 2021-10-06 11:37:01
在Excel中,假设ERIKA的日期是B2格式,我将使用以下内容:
=DATE(LEFT(B2,4),MID(B2,5,2),RIGHT(B2,2))
在VBA中的函数中,我将使用:
Function TextToDate(txt As String) As Date
TextToDate = DateSerial(Left(txt, 4), Mid(txt, 5, 2), Right(txt, 2))
End Function
发布于 2021-10-06 11:37:16
我建议将所有数据加载到一个数组中,然后运行“迁移”。使用数组来操作数据比直接处理单元格要快得多。
或者,您也可以使用公式。
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
https://stackoverflow.com/questions/69464748
复制相似问题