Excel 需要一些帮助来修复VBA中每个循环的
由于某些原因,此循环不会调用子formatCells在选择中的每个单元格上运行。它将仅在选定范围内的左上角单元格上运行Excel 需要一些帮助来修复VBA中每个循环的,excel,vba,Excel,Vba,由于某些原因,此循环不会调用子formatCells在选择中的每个单元格上运行。它将仅在选定范围内的左上角单元格上运行 Sub selectionLoop() Dim rng As Range, itm As Range Set rng = Selection For Each itm In rng Call formatCells Next End Sub Sub formatCells() 'Formats cells based on
Sub selectionLoop()
Dim rng As Range, itm As Range
Set rng = Selection
For Each itm In rng
Call formatCells
Next
End Sub
Sub formatCells() 'Formats cells based on what is in the cell
If WorksheetFunction.IsText(ActiveCell) = True Then 'Searching for text in the cell
With ActiveCell.Font 'Applies text format
.Name = "Calibri"
.Size = 18
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
.Bold = True
End With
With ActiveCell
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Else
ActiveCell.NumberFormat = "#,##0_);(#,##0)" 'Applies number format
End If
End Sub
对代码的一些改进:
IF
替换为Select Case
对代码的一些改进:
IF
替换为Select Case
传递
FormatCells
aRange
变量;不要使用ActiveCell
。或者只是将循环移动到FormatCells
。传递FormatCells
一个范围
变量;不要使用<代码> ActueCeule<代码>。或者只是把你的循环移到<代码> FrastCys<代码>。这很漂亮,谢谢,而且链接也很有帮助。敬畏的,请考虑对答案进行标记,这样别人会发现它很漂亮,谢谢,而且链接也很有帮助。请考虑批改答案,以便其他人也能找到答案。
Option Explicit
Sub selectionLoop()
Dim targetRange As Range
Dim cell As Range
Set targetRange = Selection
' Loop through each cell in range
For Each cell In targetRange
' Pass the cell to procedure
formatCells cell
Next
End Sub
Private Sub formatCells(ByVal cell As Range) 'Formats cells based on what is in the cell
If WorksheetFunction.IsText(cell.Value) = True Then 'Searching for text in the cell
With cell.Font 'Applies text format
.Name = "Calibri"
.Size = 18
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
.Bold = True
End With
With cell
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Else
cell.NumberFormat = "#,##0_);(#,##0)" 'Applies number format
End If
End Sub