首页 > 解决方案 > 强制日期单元格保留 10 个字符的日期(“mm/dd/yyyy”)

问题描述

我正在从一个网站上抓取一些数据,其中一列包含日期和日期,格式类似于Thu 09/06/2018. 我只想保留该09/06/2018部分,但似乎无论我做什么,Excel 都会将日期转换为9/6/2018. 我需要完整的09/06/2018(不仅仅是格式化的,在公式栏中可见)才能将数据接受到数据库中 - 如何强制 excel 将此数据保留为文本?

下面是我的代码,底部是我的尝试'Fix Dates

'Fix Dates
Application.CutCopyMode = False
LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
    For Each cell In Range("B2:B" & LastRow).Cells
        cell.NumberFormat = "@"
        cell.Offset(0, 9).Value = Right(cell.Value, 10)
    Next cell

    For Each cell In Range("K2:K" & LastRow).Cells
        cell.NumberFormat = "@"
        cell.Offset(0, -9).Value = cell.Value
    Next cell

Columns("K:K").EntireColumn.Delete

标签: vbaexcel

解决方案


您正在复制到 k 列,然后返回到 B 列,只需一步在 B 中完成所有操作。

'Run this loop on the cell itself rather than column K.
For Each cell In Range("B2:B" & LastRow).Cells
    cell.NumberFormat = "@"
    cell.Value = Right(cell.Value, 10) 'Removed offset
Next cell

'Remove this loop and the subsequent delete
'For Each cell In Range("K2:K" & LastRow).Cells
'    cell.NumberFormat = "@"
'    cell.Offset(0, -9).Value = cell.Value
'Next cell

'Columns("K:K").EntireColumn.Delete

推荐阅读