使用vba to date格式在excel中格式化列

时间:2016-04-14 08:45:58

标签: excel vba excel-vba date

我正在尝试重置Excel工作表的格式,问题是我有4列应该是日期格式。如何查找标题中包含“DATE”的所有列(例如:最后加工日期,装配日期,订单日期等)并将此格式更改为日期?注意:需要动态,因为它可能会在未来从C:C更改为E:E或添加更多列。

Sub formatTable(ws As Worksheet)
    On Error Resume Next
    Dim lo As ListObject
    Set lo = ws.ListObjects("FilterParts")

    'Format the table
    ws.UsedRange.Font.Bold = False
    ws.UsedRange.Style = "Normal"

    lo.TableStyle = "TableStyleMedium9"
    'Format every column that has "DATE" in its header to a date column
    'ws.Range("C:C").NumberFormat = "dd/mm/yyyy" and so on


End Sub

4 个答案:

答案 0 :(得分:3)

只需像这样遍历您的列,检查它们的名称是否包含"Date",如果是,则格式化它们:

Set lo = ws.ListObjects("FilterParts")
For Each dataColumn In lo.ListColumns
    If InStr(dataColumn.Name, "Date") > 0 Then
        dataColumn.DataBodyRange.NumberFormat = "dd/mm/yyyy"
    End If
Next dataColumn

每次添加新列时运行此宏。

答案 1 :(得分:1)

更长的编码选项,但使用Find来避免在整个范围内循环。

Dim ws As Worksheet
Dim lo As ListObject
Dim rng1 As Range
Dim StrAddress As String

Set ws = ActiveSheet
Set lo = ws.ListObjects("FilterParts")

Set rng1 = lo.Range.Rows(1).Find("Date", , , xlPart)

If Not rng1 Is Nothing Then
    StrAddress = rng1.Address
    rng1.Offset(1, 0).Resize(lo.ListRows.Count, 1).NumberFormat = "dd/mm/yyyy"
    Do
    Set rng1 = lo.Range.Rows(1).Find("Date", rng1, , xlPart)
    rng1.Offset(1, 0).Resize(lo.ListRows.Count, 1).NumberFormat = "dd/mm/yyyy"
    Loop While StrAddress <> rng1.Address
End If

答案 2 :(得分:0)

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string></string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>fb$(FACEBOOK_APP_ID)</string>
        </array>
    </dict>
</array>

从这里你可以存储一个循环的单元格/列号或立即循环这个列中的单元格....

如果您需要更多帮助,这应该让您开始回复。

答案 3 :(得分:-1)

尝试:

Range("A1","A50000").NumberFormat = "dd\/mm\/yyyy"