Fix VBA Runtime 1004 Error in Excel Program

  • Thread starter Thread starter dmatador
  • Start date Start date
  • Tags Tags
    Error Runtime
Click For Summary
SUMMARY

The discussion addresses the VBA Runtime 1004 error encountered while attempting to square values in Excel using a VBA program. The original code incorrectly defines the range and counts cells, leading to the error. The solution involves specifying a valid range, such as Range("A2:G85"), and changing the variable type for 'n' from Integer to Long to accommodate larger datasets in Excel 2007 and later. The corrected code successfully squares the values in column 'A' and outputs them to column 'B'.

PREREQUISITES
  • Basic understanding of VBA programming
  • Familiarity with Excel object model
  • Knowledge of data types in VBA, specifically Integer and Long
  • Experience with Excel ranges and cell references
NEXT STEPS
  • Learn about defining ranges in VBA, including dynamic ranges
  • Explore error handling techniques in VBA to manage runtime errors
  • Study data types in VBA for optimal memory usage
  • Investigate advanced Excel functions and their integration with VBA
USEFUL FOR

Beginner VBA programmers, Excel users automating tasks, and anyone troubleshooting runtime errors in Excel VBA scripts.

dmatador
Messages
120
Reaction score
1
This is my first attempt at writing a VBA program. I am just trying to square items in excel in column 'A' and output the answer to column 'B'.

Option Explicit

Sub timestimes()
Dim n As Integer
Dim i As Integer
Dim z As Integer

n = Range("A").Count

For i = 1 To n
z = Range("A").Cells(i).Value
Range("B").Cells(i).Value = z * z * z
Next i
End Sub

It's giving me the previously noted runtime error along with the message Method 'Range' of object '_global' failed. I am clueless as to how to fix this problem since I know very very little about the language and working with excel like this. Any suggestions?
 
Technology news on Phys.org
I see two problems:

1) "A" isn't a range. You need something like: Range("A2:G85")

2) You can't count a range. You count cells within a range. Example: n = Range("A1:B33").Cells.Count

You can use n = Columns("A").Cells.Count but you'll get an overflow error if you are using Excel 2007 because an integer can't hold that big a number (1048576). You'd need to declare n as a Long.
 
Last edited:
Thanks. It is working now.
 

Similar threads

  • · Replies 17 ·
Replies
17
Views
7K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 2 ·
Replies
2
Views
9K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
Replies
12
Views
9K
Replies
13
Views
8K
  • · Replies 1 ·
Replies
1
Views
2K