【问题标题】:Set Excel cell equal to string containing date without leading apostrophe将 Excel 单元格设置为等于包含日期且不带前导撇号的字符串
【发布时间】:2018-08-28 09:06:20
【问题描述】:

我有一些代码使用.CopyFromRecordset 将字符串写入 Excel 工作表。此记录集包含看起来像日期和数字的字符串,例如 109-08-2018,这些字符串正确地保留为字符串。

我最近添加了一些额外的处理来调整一些单元格值。但是,当将值写回单元格时,我无法保留它们的当前状态(字符串、格式:一般、没有前导撇号)。

以下代码说明了我的问题:

Public Sub MCVE()
    With Range("A1")
        Debug.Print .Value '09-08-2018
        Debug.Print .Value2 '09-08-2018
        Debug.Print VarType(.Value) = vbString 'True
        Debug.Print .NumberFormat 'General
        Debug.Print .PrefixCharacter 'Zero-length string
        .Value = .Value 'I want to manipulate the value here too
        '.Value2 = .Value2 'Yields the same result
        Debug.Print .Value '08-09-2018
        Debug.Print .Value2 '43351
        Debug.Print VarType(.Value) = vbString 'False
        Debug.Print .NumberFormat 'm/d/yyyy
        Debug.Print .PrefixCharacter 'Zero-length string
    End With
End Sub

我可以手动将.NumberFormat 设置为 @ 以强制将其转换为文本,但随后.NumberFormat.PrefixCharacter 都发生了变化,这会在将其导入另一个程序时进一步造成麻烦.我也可以在分配之前用撇号填充字符串,但这也会改变.PrefixCharacter

我尝试使用.Value2 代替.Value,没有区别。 .Text 是只读的,所以我不能用它来分配。设置Application.Calculation = xlCalculationManual 之类的东西也没有影响。

这似乎很简单,但经过数小时的尝试,我还没有找到可行的解决方案。

【问题讨论】:

  • 您正在使用哪个 excel 版本?
  • @ImranMalek Excel 2016,构建 8201,32 位,但我也可以在 2010 年重现。
  • 如果您尝试在 General 格式的单元格中输入 08-09-2018 作为 value 并阻止 Excel 自动将其转换为日期,那么,在我的认为这是不可能的。
  • 您正在导入 DMY 文本日期,而您的系统显然是 MDY。修复日期导入。
  • @Jeeped 我根本不想导入日期!这是一个字符串,而不是日期

标签: vba excel


【解决方案1】:

以下代码:

Public Sub MCVE()
    Dim OldFormat As String
    With Range("A1")
        OldFormat = .NumberFormat
        .NumberFormat = "@"
        .Value = .Value 
        .NumberFormat = OldFormat
    End With
End Sub

解决了 Excel 2010 和 2013 中的问题,但(如 cmets 中所报告)在 2016 年将 PrefixCharacter 更改为撇号。

这个版本似乎适用于所有版本:

Public Sub MCVE()
    With Range("A1")
        .NumberFormat = "@"
        .Value = .Value 
        .ClearFormats
    End With
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    • 2021-08-28
    • 2015-10-02
    相关资源
    最近更新 更多