通过变型直接值传输保留数据类型

时间:2019-03-19 00:08:07

标签: excel vba

我一直在尝试研究如何使用变体和直接值传递来保留数据类型。我有一列的值例如

0001
A001
0B02
ZZZ1

我正在根据列名将值从一个表转移到另一个表。

Dim x As Variant
Dim mc As Variant
Dim lc As Long 

x = raw_tbl.ListColumns(mc).DataBodyRange.Value
                .ListColumns(lc).DataBodyRange = x

此刻,如果我复制上面的列表,它将丢失数据格式并变为以下内容。

1
A001
0B02
ZZZ1

如何保留列的数据类型?我希望它是文本而不是数字,所以0001保持为0001而不是数字1

1 个答案:

答案 0 :(得分:1)

也许是这样的:

Sub CopyOverMatches()

    Dim tbl1 As ListObject, tbl2 As ListObject
    Dim h As ListColumn, h2 As ListColumn, data

    Set tbl1 = ActiveSheet.ListObjects("Table1")
    Set tbl2 = ActiveSheet.ListObjects("Table2")

    'loop over the headers from the source table
    For Each h In tbl1.ListColumns

        'is there a column of the same name in the destination table?
        Set h2 = Nothing
        On Error Resume Next
        Set h2 = tbl2.ListColumns(h.Name)
        On Error GoTo 0

        If Not h2 Is Nothing Then '<< have a matching column

            data = h.DataBodyRange.Value

            With h2.DataBodyRange.Cells(1).Resize(UBound(data, 1), 1)
                .NumberFormat = h.DataBodyRange(1).NumberFormat
                .Value = data
            End With

        End If
    Next h

End Sub