Small Coding Problem for Excel Macro

  • Thread starter Thread starter darkchild
  • Start date Start date
  • Tags Tags
    Coding Excel
Click For Summary
SUMMARY

The discussion centers on creating a Visual Basic for Applications (VBA) macro to insert two rows above a specified row number in Excel. The user initially encounters a syntax error in the range specification within the macro. The correct syntax for defining the range is provided as CurrentSheet.Range("a" & x & ":a" & (x+1)).EntireRow.Insert, which resolves the issue. However, the user later reports that this solution inadvertently deleted existing data, leading them to seek alternative macros.

PREREQUISITES
  • Familiarity with Visual Basic for Applications (VBA) syntax
  • Understanding of Excel object model and ActiveWindow properties
  • Basic knowledge of Excel ranges and row manipulation
  • Experience with debugging and error handling in VBA
NEXT STEPS
  • Research Excel VBA error handling techniques to prevent data loss
  • Learn about the Excel object model for better manipulation of sheets and ranges
  • Explore advanced VBA techniques for dynamic row insertion
  • Investigate alternative methods for batch row insertion in Excel
USEFUL FOR

This discussion is beneficial for Excel users, VBA developers, and anyone looking to automate tasks in Excel through macros, particularly those interested in row manipulation and error resolution in VBA scripts.

darkchild
Messages
153
Reaction score
0
I want to code a macro that will take in an integer as a row number and insert two rows above that row. This will repeat in a for loop. The problem is that I'm not familiar with VB syntax. Here's what I have so far:

Sub Insert_Rows_Loop()
Dim CurrentSheet As Object
Dim x As Integer

' Loop through all selected sheets.
For Each CurrentSheet In ActiveWindow.SelectedSheets
For x = 14 To 418
' Insert 2 rows depending on values of a1 and a2.
CurrentSheet.Range("a" & x &:"a" & (x+1)&").EntireRow.Insert
Next x
Next CurrentSheet
End Sub

There is some sort of syntax error in the CurrentSheet.Range argument. How does one specify a range with a variable?

Thanks.
 
Computer science news on Phys.org
Try this...

CurrentSheet.Range("a" & x & ":a" & (x+1)).EntireRow.Insert
 
Thanks, but that just deleted everything :) I found another macro to use.
 

Similar threads

  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 18 ·
Replies
18
Views
6K
  • · Replies 6 ·
Replies
6
Views
55K
Replies
1
Views
12K
  • · Replies 1 ·
Replies
1
Views
5K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 9 ·
Replies
9
Views
6K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 11 ·
Replies
11
Views
10K