当某些单元格为空白时,VBA代码将继续使用文本格式进行格式化

由于我的VBA知识并不广泛,我通常会logging我需要的macros。 因为我在同一个单元格中同时具有date和时间的列,所以我使用Excel的“文本到列”function并logging下来,提供下面的代码。 但是,一旦任何一行中有一个空白单元格,下面的所有单元格都没有格式化!

在我的search中,我发现解决scheme是基于循环的代码来执行单元格的操作,但我还没有find如何使用它来做什么,再加上看起来非常复杂!

我问是否有办法忽略空白单元格,并继续格式化。

这是文本到列的代码,但有代码,我可以添加之前或之后忽略空白单元格,仍然保持下面的代码?

Columns("S:S").Select Selection.Insert Shift:=xlToRight Range("R2").Select Range(Selection, Selection.End(xlDown)).Select Selection.TextToColumns Destination:=Range("R2"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 2), Array(9, 1)), TrailingMinusNumbers:=True Columns("S:S").Select Selection.Delete Shift:=xlToLeft Columns("T:T").Select Selection.Insert Shift:=xlToRight Range("S2").Select Range(Selection, Selection.End(xlDown)).Select Selection.TextToColumns Destination:=Range("S2"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 2), Array(9, 1)), TrailingMinusNumbers:=True Columns("T:T").Select Selection.Delete Shift:=xlToLeft Columns("U:U").Select Selection.Insert Shift:=xlToRight Range("T2").Select Range(Selection, Selection.End(xlDown)).Select Selection.TextToColumns Destination:=Range("T2"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 2), Array(9, 1)), TrailingMinusNumbers:=True Columns("U:U").Select Selection.Delete Shift:=xlToLeft 

更改,

 Range(Selection, Selection.End(xlDown)).Select 

… 至,

 Range(Cells(2, "T", Cells(Rows.Count, "T").End(xlUp)).Select 

"T"更改为适当的列。

我虚心地build议你避免使用Range .Select和Range .Activate方法来完成你的任务。 logging的代码是一个很好的开始方式,但是如果您打算保留代码以备将来使用,则应该准备修改代码以删除“select”和“select”。 请参阅如何避免使用Excel中的selectVBAmacros来获取更多的方法来摆脱依靠select和activate来实现您的目标。

例如:

 With Worksheets("Sheet1") .Columns("S:S").Insert Shift:=xlToRight With .Range(.Cells(2, "R"), .Cells(Rows.Count, "R").End(xlUp)) .TextToColumns Destination:=.Range("R2"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 2), Array(9, 1)), _ TrailingMinusNumbers:=True End With .Columns("S:S").Delete Shift:=xlToLeft .Columns("T:T").Insert Shift:=xlToRight With .Range(.Cells(2, "S"), .Cells(Rows.Count, "S").End(xlUp)) .TextToColumns Destination:=.Range("S2"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 2), Array(9, 1)), _ TrailingMinusNumbers:=True End With .Columns("T:T").Delete Shift:=xlToLeft .Columns("U:U").Insert Shift:=xlToRight With .Range(.Cells(2, "T"), .Cells(Rows.Count, "T").End(xlUp)) .TextToColumns Destination:=.Range("T2"), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, 2), Array(9, 1)), _ TrailingMinusNumbers:=True End With .Columns("U:U").Delete Shift:=xlToLeft End With 

使用循环遍历列R,S和T(第18,19和20列)将进一步清理您的代码。

 Dim c As Long With Worksheets("Sheet1") For c = 18 To 20 With .Range(.Cells(2, c), .Cells(.Rows.Count, c).End(xlUp)) .TextToColumns Destination:=.Cells(1), DataType:=xlFixedWidth, _ FieldInfo:=Array(Array(0, xlMDYFormat), Array(10, xlSkipColumn)) End With Next c End With 

我已经应用xlMDYFormat到date。 如果您的date是DMY,则使用xlDMYFormat或使用xlColumnDataType Enumeration检查其他可用的格式。