簡體   English   中英

需要一些幫助來修復 VBA 中的 For Each 循環

[英]Need some help fixing a For Each loop in 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 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

對您的代碼的一些改進:

  1. 使用選項顯式避免未聲明變量的麻煩
  2. 將變量命名為有意義的名稱
  3. 不要依賴 ActiveCell除非你真的是認真的
  4. 可選:用Select Case替換您的IF

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM