问题
I have a VBA macro that worked correctly in Excel 2007 but after updating to 2010 it throws errors. The Macro basically copies raw data from one sheet to multiple sheets. The error being thrown is error 6: Overflow. The line that is throwing the error is Dim
y As Integer
y = Worksheets("Raw Data").Range("A2").End(xlDown).Row
I initially thought ok ill change it to long and it will kill the overflow error. Well i guess it killed the error but it also output very wrong results and then relized that the overflow error doesnt even make sense... there is only 973 rows.
I then thought ok maybe ill try this instead
Cells(Rows.Count,"A").End(xlUp).Offset(1,0).Select
Now it throws "Run-time error '1004' method 'range' of object '_global' failed" on the line after.
below is a portion of the full code. I am usure of how it could even be a overflow error? Any help is appreciated.
Dim y As Integer
'y = Worksheets("Raw Data").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).Select
y = Worksheets("Raw Data").Range("A2").End(xlDown).Row
Range("B1:U" & y).Select
Selection.Copy
Sheets("Yellow Suppliers").Select
Range("B2").Select
ActiveSheet.Paste
Columns("C:E").Select
Selection.Delete Shift:=xlToLeft
Columns("P:Q").Select
Selection.Delete Shift:=xlToLeft
Columns("A").ColumnWidth = 2.14
Columns("B").ColumnWidth = 43.43
Columns("C").ColumnWidth = 12.14
Columns("D:O").ColumnWidth = 8
Columns("P").ColumnWidth = 10.14
Rows("1").RowHeight = 15
Rows("2:" & y).RowHeight = 30
Range("B3:B22").Select
Selection.Font.Bold = True
回答1:
Integers in VBA are 16 bit signed numbers which means that the largest value they can take is 32767. There can be many more rows in a spreadsheet than that in the new Excel versions.
You need to use a long rather than an integer. A long is a 32 bit signed; plenty big enough.
So change Dim y As Integer
to Dim y as Long
In fact I'm suprised it worked in Excel 2003 as that, if my memory is correct, has 65536 rows. But try my suggestion anyway as your code is definitely incorrect.
回答2:
Try getting rid of any Select
or Selection
in your code. Also, confirm that y
indeed does evaluate to the expected value of 973
.
Sub Macro2()
Dim rngY as Range '## a variable to calculate the size of rows used in Column A'
Dim y As Integer
With Worksheets("Raw Data")
Set rng = .Range("A2").Resize( _
Application.WorksheetFunction.CountA(.Range("A:A")))
End With
y = rngY(rngY.Rows.Count).Row
Range("B1:U" & y).Copy Destination:= _
Sheets("Yellow Suppliers").Range("B2")
Columns("C:E").Delete Shift:=xlToLeft
Columns("P:Q").Delete Shift:=xlToLeft
Columns("A").ColumnWidth = 2.14
Columns("B").ColumnWidth = 43.43
Columns("C").ColumnWidth = 12.14
Columns("D:O").ColumnWidth = 8
Columns("P").ColumnWidth = 10.14
Rows("1").RowHeight = 15
Rows("2:" & y).RowHeight = 30
Range("B3:B22").Font.Bold = True
End Sub
来源:https://stackoverflow.com/questions/16696891/vba-overflow-error-after-office-2007-to-2010-update