这是循环遍历范围内所有值的替代方法。
Dim lngRows As Long
Dim lngColumns As Long
Dim rngStartingCell As Range
Dim rngItems As Range
lngColumns = InputBox("Input Number Of Items")
lngRows = InputBox("How Many Items For Each Item")
Set rngStartingCell = [G1] 'Change to your starting cell
Set rngItems = rngStartingCell.Resize(lngRows, lngColumns)
With rngItems
.Formula = "=""Item_"" & SUBSTITUTE(ADDRESS(ROW(),COLUMN()),""$"","""")"
'The Following Line is Optional But it well remove the formula from the cells
'Leaving only the Desired results
.Value = .Value
End With
但我喜欢在我的代码周围放置一个包装器,如下所示,这将提高代码的性能。如果您有工作表事件,有助于避免无限循环
Sub Sample()
'Save Settings, Then turn them all off
'///////////////////////////////////////////////////////////////////////////////////////////////
With Application
Dim StartingScreenUpdateing As Boolean
Dim StartingEnabledEvent As Boolean
Dim StartingCalculations As XlCalculation
StartingScreenUpdateing = .ScreenUpdating
StartingEnabledEvent = .EnableEvents
StartingCalculations = .Calculation
.ScreenUpdating = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
'///////////////////////////////////////////////////////////////////////////////////////////////
Dim lngRows As Long
Dim lngColumns As Long
Dim rngStartingCell As Range
Dim rngItems As Range
lngColumns = InputBox("Input Number Of Items")
lngRows = InputBox("How Many Items For Each Item")
Set rngStartingCell = [G1] 'Change to your starting cell
Set rngItems = rngStartingCell.Resize(lngRows, lngColumns)
With rngItems
.Formula = "=""Item_"" & SUBSTITUTE(ADDRESS(ROW(),COLUMN()),""$"","""")"
'The Following Line is Optional But it well remove the formula from the cells
'Leaving only the Desired results
.Value = .Value
End With
'Restore starting settings.
'///////////////////////////////////////////////////////////////////////////////////////////////
With Application
.ScreenUpdating = StartingScreenUpdateing
.EnableEvents = StartingEnabledEvent
.Calculation = StartingCalculations
End With
'///////////////////////////////////////////////////////////////////////////////////////////////
End Sub