简体   繁体   English

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

[英]Format column in excel with vba to date format

I am trying to reset the formatting of my excel sheet, the problem is that I have 4 columns which should be date format. 我正在尝试重置我的Excel工作表的格式,问题是我有4列应该是日期格式。 How can I find all columns which contain "DATE" in header (Such as : last machined date, assembly date, order date etc..) and change this format to date? 如何查找标题中包含“DATE”的所有列(例如:最后加工日期,装配日期,订单日期等)并将此格式更改为日期? Note: Needs to be dynamically because it might change from C:C to E:E in the future or more columns added. 注意:需要动态,因为它可能会在未来从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

Just iterate through your columns like this, check if their names contain "Date" and if yes, then format them: 只需遍历您的列,检查它们的名称是否包含"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

Run this macro every time you add a new column. 每次添加新列时都运行此宏。

A longer coding option but uses Find to avoid looping through the range. 较长的编码选项,但使用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
Dim HdrRow as range
Dim Cl as Range
Set HdrRow = ActiveSheet.UsedRange
Set HdrRow = HdrRow.Row(1) 'assuming row 1 of the data contains headers

For Each Cl In HdrRow.cells
    If Instr(lCase(Cl.Value), "date") > 0 then 'This column has "date" in the header text
enter code here
Next Cl

from here you can either store the cell/column number for a loop later or loop the cells in this column right away.... 从这里你可以存储一个循环的单元格/列号或立即循环此列中的单元格....

this should get you started just post back if you need more help. 如果您需要更多帮助,这应该让您开始回复。

尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM