Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inserting Excel Rows via VBScript

Status
Not open for further replies.

griffinmt

Technical User
Nov 21, 2000
9
US
I am going to give this one more try.
I am having some difficulty with determining the line of code that will allow me to insert a new row above the currently selected cell. The code created when you record a macro and do this manually will not work when transported to VBScript.

Here is a snippet of code, with the offending line bolded in red.

Code:
Set oEx = GetObject("","Excel.Application")
oEx.Visible = true
oEx.Workbooks.open "C:\test.xls"
Set oWS = oEx.ActiveWorkbook.Sheets("Sheet1")
oWS.Activate
Toprow = 1
Bottomrow = 8

For i = Toprow to Bottomrow
	oWS.Range("a1").Offset(i,0).Select
	If oWS.Range(&quot;a1&quot;).Offset(i+1,0) <> &quot;&quot; Then
oWS.Selection.EntireRow.Insert
Code:
        oWS.Range(&quot;a1&quot;).Offset(i,0).Select
	End If
	oWS.Range(&quot;a1&quot;).Offset(i,0) = &quot;Stuff&quot; & i
	oWS.Range(&quot;a1&quot;).Offset(i,1) = &quot;More Stuff&quot; & i
Next

Try this on a simple sheet with any data in cell A1 and in A5 and the rest empty.

Desperately wanting an approach!!!


 
Hi

This code should work for you
Code:
   Dim oEX  'As Excel.Application
   Dim oWB  'As Excel.Workbook
   Dim oWS  'As Excel.Worksheet

   Dim lTopRow       'As Long
   Dim lBottomRow    'As Long
   Dim iIndex        'As Integer

   Set oEX = CreateObject(&quot;Excel.Application&quot;)
   Set oWB = oEX.Workbooks.Open(&quot;d:\book3.xls&quot;)
   Set oWS = oWB.Sheets(&quot;Sheet1&quot;)

   oEX.Visible = True
   oWS.Activate
   lTopRow = 1
   lBottomRow = 8

   For iIndex = lTopRow To lBottomRow
      oWS.Range(&quot;A1&quot;).Offset(iIndex + 1, 0).Select

      If oWS.Range(&quot;A1&quot;).Offset(iIndex + 1, 0) <> &quot;&quot; Then
         With oEX.Selection
            .EntireRow.Insert
         End With
      End If
   Next 

   If Not oWB Is Nothing Then
      With oWB
         .Save
         .Close
      End With
   End If

   Set oWB = Nothing
   Set oWS = Nothing

   If Not oEX Is Nothing Then
      oEX.Quit
   End If

   Set oEX = Nothing
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top