Excel范围格式未按预期呈现(转换问题)

时间:2018-07-04 10:36:44

标签: excel-vba ado vba excel

上下文:我有一个名为“ ForUser”的工作表,第一行定义标题,第二行对应数据。我还有第二张名为“ ForBuffer”的工作表,用于从数据库中检索数据。

enter image description here

“ ForUser”中的每个列都与一种格式关联,可以动态应用(格式可以由用户设置和更改)。在下面的示例中,“ ForUser”表中有一个值为“ Att $”的列标题,格式为美元。

    Dim objRs As ADODB.Recordset
    Dim rngDataBuffer As Range
    With Application.Workbooks(ThisWorkbook.Name()).Sheets("ForBuffer")
        Set rngDataBuffer = .Range("A1")
    End With
    rngDataBuffer.CopyFromRecordset Data:=objRs

从数据库中逐列加载数据,并使用 CopyFromRecordset 将数据参数设置为有效的 ADODB.Recordset 复制到一个范围内,该表称为“ ForBuffer” “

  Dim rDest As Range
  With Application.Workbooks(ThisWorkbook.Name()).Sheets("ForBuffer")
      With .Range("A1").CurrentRegion
       set rDest= .rows(1).Find( _
          What:="Att $", MatchCase:=True, LookIn:=xlFormulas, lookAt:=xlWhole)
      End With
  End With 

然后将该缓冲区复制到定义“ Att $”标题的列中的“ ForUser”表。有些单元格设置了一个值,而有些则没有。

  rngDataBuffer.Copy Destination:=rDest

我本可以使用类似的东西直接在rDest中复制存储在 objRs 中的数据(但这不是重点)

rDest.Offset(1).CopyFromRecordset Data:=objRs

要保留具有“ Att $”标头的第一行,必须使用Offset(1)。

数据在数据库侧另存为字符串,因此在 rngDataBuffer

中包含字符串

然后,我使用类似以下格式的格式:

 rDest.Offset(1).Resize(rDest.rows.count-1).NumberFormat = "#,##0.00 [$USD]"

对于我使用的其他类型(美元货币,文本,百分比,浮点数,整数)

                    .NumberFormat = "#,##0.00 $"
                    .NumberFormat = "@"
                    .NumberFormat = "0.00%"
                    .NumberFormat = "0.0"
                    .NumberFormat = "0"

我可以检查格式是否已设置但未呈现,可能是因为数据已作为字符串复制。

enter image description here

如何将一系列单元格转换为某种“类型”(在这里我说“类型”,因为“格式”似乎只是它的外观)。 ?

我尝试从某些单元格复制值1,然后使用不同的选项复制PasteSpecial。我可以得到期望的格式,但是这样做的缺点是在没有内容(空或空)的单元格中设置了0(零)。在我的应用程序上下文中,零单元格值或空单元格具有不同的含义。同样,此解决方案也无法显示日期。

我还尝试根据类型转换数据。它始终失败,并显示一条非常明确的消息:类型不匹配(错误13)。值是一个字符串,但实际上它们可以转换为期望的类型。转换将应用于范围值(多个单元格)

日期

 .Value = CDate(.Value)

对于数字“类型”(分别为整数,浮点数和货币)

.Value = CLgn(.Value)
.Value = CDbl(.Value)
.Value = CCur(.Value)

这些都不起作用。

我想出了一些让我非常惊讶的东西

.Value = .Value 

到底是什么,我应该问一下这背后的魔力是什么。顺便说一下,这适用于日期,货币和双精度,而不是整数,也不是百分比!

1 个答案:

答案 0 :(得分:0)

我不确定这是否可以回答您的问题,但这可能会有所帮助,以下内容会将指定范围转换为“货币”(忽略空白单元格):

Sheets("Sheet1").Range("B1:B13").Style = "Currency"
'set the currency format for a specified range

或更具体地说,您可以执行以下操作:

Dim rng As Range, c as Range
Set rng = Range("A1:A50") 'set the range to be used

For Each c In rng 'for each cell in the specified range
    If c.Value <> "" Then c.NumberFormat = "$#,##0.00"
    'if cell is not blank then format it
Next c

更新:

Dim rng As Range, c as Range
Set rng = Range("A1:A50") 'set the range to be used

For Each c In rng 'for each cell in the specified range
    If c.Value <> "" Then c.NumberFormat = "$#,##0.00"
    'if cell is not blank then format it
    c.Value = c.Value
    'force the format into the cell
Next c