VBA宏扫描标题行和更改列数据类型

时间:2018-02-19 15:12:02

标签: excel vba excel-vba

我经常将SSMS查询结果中的数据粘贴到Excel中,然后从那里进一步分析数据。

将日期时间戳粘贴到Excel中时,格式非常混乱。我经常发现自己将这些列更改为ShortDate数据类型。

我想要完成的是编写一个宏来扫描第1行的任何标题,例如'%Date%'并将整个列更改为ShortDate数据类型。

有人能指出我的方向开始吗?谢谢!

4 个答案:

答案 0 :(得分:1)

试试这段代码

Sub Test()
    Dim c As Range

    For Each c In Range("A1").CurrentRegion.Rows(1).Cells
        If InStr(LCase(c.Value), "date") > 0 Then
            c.EntireColumn.NumberFormat = "m/d/yyyy"
        End If
    Next c
End Sub

答案 1 :(得分:1)

您可以使用Find功能查找标题行中包含单词date的字段(在我的示例中使用第1行),然后将NumberFormat应用于它们< / p>

Public Sub FormatDates()
    Dim firstAddress As String
    Dim HeaderRow As Long
    Dim c As Range

    ' Change to your header row
    HeaderRow = 1
    ' Change to your sheet
    With Sheet1
        With .Range(.Cells(HeaderRow, 1), .Cells(HeaderRow, .Cells(HeaderRow, .Columns.Count).End(xlToLeft).Column))
            Set c = .Find(what:="Date", lookat:=xlPart)

            If Not c Is Nothing Then
                firstAddress = c.Address
                Do
                    Debug.Print c.Address
                    c.EntireColumn.NumberFormat = "dd/mm/yy"
                    Set c = .FindNext(c)
                Loop While Not c Is Nothing And c.Address <> firstAddress
            End If
        End With
    End With
End Sub

答案 2 :(得分:1)

这应该这样做:

Sub changeDateFormat()
Dim i As Long
  With ThisWorkbook.Sheets(1)
    For i = 1 To Application.CountA(.Rows(1))
      If LCase(.Cells(1, i).Value2) Like "*date*" Then .Columns(i).NumberFormat = "dd/mm/yyyy"
    Next i
  End With
End Sub

答案 3 :(得分:1)

查看标题列标签几乎已经处理好了,所以我将解决数据本身的问题。

dim c as long
with worksheets(1)
    with .cells(1, 1).currentregion
        for c=1 to .columns.count
            'this only looks at the second row; a nested loop here could look at more rows
            if isdate(.cells(2, c)) then .columns(c).numberformat = "m/d/yyyy;@"
        next c
    end with
end with