问题
I am trying to loop through different sheets in my workbook. I have tried searching through stackoverflow but still stuck with the error. The error showed "Method 'Range' of object'_Worksheet' failed.
The purpose of this code is to standardise all formats in the worksheets.
Sub formatting()
Dim ws as Worksheet
Dim lastRow as long, lastColumn as long
lastRow = Range("A" & Rows.Count).End(xlUp).Row
lastColumn = (Cells(1, Columns.Count).End(xlToLeft).Column)
For each ws in Activeworkbook.Worksheets
With ws.Range(cells(lastRow, 1), cells(1, lastColumn))
'rest of the actions I want to perform'
.font.bold = true
End With
Next ws
End Sub
I just got started on Excel vba, please enlighten me! Thank you!
回答1:
Few changes to be made: 1. You have to redefine the last row and last column for each sheet. With that said, place the variable assignment inside the loop.
- Instead of
ws.Range(cells...), the proper syntax isRange(ws.cells...)
See below:
Sub formatting()
Dim ws As Worksheet
Dim lastrow As Long, lastcolumn As Long
For Each ws In ActiveWorkbook.Worksheets
lastrow = ws.Range("A" & Rows.Count).End(xlUp).Row
lastcolumn = (Cells(1, Columns.Count).End(xlToLeft).Column)
With Range(ws.Cells(1, 1), ws.Cells(lastrow, lastcolumn))
'rest of the actions I want to perform'
.Font.Bold = True
End With
Next ws
End Sub
回答2:
You have to qualify the Cells calls as well as the Range call:
With ws.Range(ws.cells(lastRow, 1), ws.cells(1, lastColumn))
回答3:
If you just got started in VBA I'd learn about setting ranges using .currentregion this will greatly help you in the future.
The code snippet makes all fields bold. If you are applying to all then currentregion can save code and possible errors on one condition "that all the fields are connected."
Sub formattingWithCurrentRegion()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Range("A1").CurrentRegion.Font.Bold = True
Next ws
End Sub
By setting the area as a range you can get greater control over ranges to set different formatting without having to deal with loops in loops. See below
Sub formattingWithCurrentRegion()
Dim ws As Worksheet
Dim rSheet As Range
For Each ws In ActiveWorkbook.Worksheets
'' sets the CurrentRegion as a range. Use the immediate window rSheet.Select to see what CurrentRegion does.
Set rSheet = ws.Range("A1").CurrentRegion
'' now you can work with it
rSheet.Font.Bold = True
'' make the 2 column font.color to Red
rSheet.Resize(rSheet.Rows.Count, 1).Offset(0, 1).Font.Color = vbRed
''now clean up. Always set ranges to nothing when done with them.
Set rSheet = Nothing
Next ws
End Sub
来源:https://stackoverflow.com/questions/28323053/excel-vba-range-object-error-in-looping-through-worksheet