根据标题 – Excel格式化一系列的列

我有一个解决scheme的一部分,但它不是像我希望的工作,所以我来找你的意见。

我经常收到Excel文件,我需要修改格式。 我正尝试通过尽可能多地自动化这些过程来学习VBA。

我完成一个特定的格式是将date转换为“DDMMYYYY”(09091986),通常在09/09/1986。

在我的工作表中,总共有3个包含date的列,所有这些列都需要相同的格式,并且在标题中都有“DATE”字样。 他们不相邻。

我还必须小心,不要有任何其他数据的影响,因为我有姓名和地址可能包含字符“date”。

所以,背景的方式…我试图search第一行,直到我find单词“date”,然后格式化每个单元格,直到最后一行,然后再移动到包含单词“ DATE“并重复此操作,直到所有包含单词”DATE“的列都被格式化。

我相信你有一个简单的解决scheme,但我似乎无法自己find它。

这是我有的代码…

Sub Dateformat() Dim LastRow As Integer Dim FindCol As Integer Dim C1 As Integer LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row FindCol = Cells.Find(What:="DATE", LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Column For C1 = 2 To LastRow Cells(C1, FindCol).NumberFormat = "DDMMYYYY" Next C1 End Sub 

这适用于包含date的第一列,但不移动到下一列。

谢谢您的帮助

问候,亚当

如您所知,您需要循环查找每个行标题与DATE

这是一个办法。

 Sub Dateformat() Dim wks As Worksheet Dim LastRow As Integer Dim rFound As Range Dim sAdd As String Set wks = ThisWorkbook.Sheets("Sheet1") ' adjust as needed With wks LastRow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row 'find first instance where DATE exists in row 1 (headers) Set FindCol = .Rows(1).Find(What:="DATE", LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False) 'store address of first found instance (to check in loop) sAdd = FindCol.Address Do 'format column (row 2 to last used row) .Range(.Cells(2, FindCol.Column), .Cells(LastRow, FindCol.Column)).NumberFormat = "DDMMYYYY" 'this line works as well and is a bit cleaner '.Cells(2, FindCol.Column).Resize(LastRow - 1, 1).NumberFormat = "DDMMYYYY" 'find next instance (begin search after current instance found) Set FindCol = .Cells.FindNext(After:=FindCol) 'keep going until nothing is found or the loop finds the first address again (in which case the code can stop) Loop Until FindCol Is Nothing Or FindCol.Address = sAdd End With End Sub