我的excel工作表中有几列,都被命名为“Date”。我想编写一个代码,它将在所有工作表中找到所有日期列,并将该列中的值格式化为“dd / mm / yyyy; @”。
在下面的代码中,我尝试编写列(“日期”)。选择而不是列(“E:E”)。选择但这不起作用。任何人都可以建议我如何解决这个问题?
感谢您的时间和建议。
Sub dateformat()
Dim ws As Worksheet
For Each ws In Worksheets
Columns("E:E").Select
Selection.NumberFormat = "dd/mm/yyyy;@"
Next ws
End Sub
答案 0 :(得分:2)
Nupur,这是你在尝试的吗?
Option Explicit
Sub Sample()
Dim aCell As Range, bCell As Range
Dim ws As Worksheet
Dim ExitLoop As Boolean
For Each ws In ThisWorkbook.Sheets
Set aCell = ws.Rows(1).Find(what:="Date", LookIn:=xlValues, _
lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
ExitLoop = False
If Not aCell Is Nothing Then
Set bCell = aCell
ws.Columns(aCell.Column).NumberFormat = "dd/mm/yyyy;@"
Do While ExitLoop = False
Set aCell = ws.Rows(1).FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
ws.Columns(aCell.Column).NumberFormat = "dd/mm/yyyy;@"
Else
ExitLoop = True
End If
Loop
End If
Next
End Sub
<强>后续强>
您收到这些错误的原因是您的列格式为文本。试试这个。这有效:)
Option Explicit
Sub Sample()
Dim aCell As Range, bCell As Range
Dim ws As Worksheet
Dim lastRow As Long, i As Long
Dim ExitLoop As Boolean
For Each ws In ThisWorkbook.Sheets
Set aCell = ws.Rows(1).Find(what:="Date", LookIn:=xlValues, _
lookat:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
ExitLoop = False
If Not aCell Is Nothing Then
Set bCell = aCell
ws.Columns(aCell.Column).NumberFormat = "dd/mm/yyyy;@"
lastRow = ws.Range(Split(ws.Cells(, aCell.Column).Address, "$")(1) & _
ws.Rows.Count).End(xlUp).Row
For i = 2 To lastRow
With ws.Range(Split(ws.Cells(, aCell.Column).Address, "$")(1) & i)
.FormulaR1C1 = .Value
End With
Next i
ws.Columns(aCell.Column).AutoFit
Do While ExitLoop = False
Set aCell = ws.Rows(1).FindNext(After:=aCell)
If Not aCell Is Nothing Then
If aCell.Address = bCell.Address Then Exit Do
ws.Columns(aCell.Column).NumberFormat = "dd/mm/yyyy;@"
lastRow = ws.Range(Split(ws.Cells(, aCell.Column).Address, "$")(1) & _
ws.Rows.Count).End(xlUp).Row
For i = 2 To lastRow
ws.Range(Split(ws.Cells(, aCell.Column).Address, "$")(1) & i).FormulaR1C1 = _
ws.Range(Split(ws.Cells(, aCell.Column).Address, "$")(1) & i).Value
Next i
Else
ExitLoop = True
End If
Loop
End If
Next
End Sub
HTH
西特
答案 1 :(得分:0)
你能加入一些代码(修改以适应你的需求)吗?
varLookFor1 = Format(Date - 1, "[$-409]mmmm-yy;@")
ActiveWorkbook.ActiveSheet.Cells.Find(What:=varLookFor1, LookIn:=xlValues).Activate