I'm building VBA inside Access to modify an Excel file. Â I have two fields on my form (txtFileNa and cmbWorksheet) that contain the path&file ("C:\Spreadsheets\Problem.xlsx") and the worksheet name ("ThisSpreadsheet"). Â
 I need to specify a worksheet for inserting and populating a new column.  The code below works fine as long as I'm putting the column in the first worksheet in the workbook, but if I need to put the column in the 4th worksheet (named "ThisSpreadsheet"), it still goes in the first worksheet.  I've tried these changes on line 90:
  90   Set xlSheet = xlBook.Worksheets(4)
  90   Set xlSheet = xlBook.Worksheets("ThisSpreadsheet")
  90   Set xlSheet = xlBook.Worksheets(me.cmbWooksheet)
neither of them work. Â I think I need to modify lines 100 and 110 to specify the worksheet, but I don't know how. Â I'd appreciate any suggestions for making the code better, in addition to fixing the specification issue. Â Thanks!
Dim xl As Excel.Application, xlBook As Excel.Workbook, xlSheet As Excel.Worksheet, filePath As String
  Â
60 Â Â filePath = Me.txtFileNa
70 Â Â Set xl = New Excel.Application
80 Â Â Set xlBook = xl.Workbooks.Open(filePath)
90 Â Â Set xlSheet = xlBook.Worksheets(1)
     Â
'add new column to spreadsheet
100 Â Range("A1").EntireColumn.Insert
'put description in header row:
110 Â Range("$A$1").Value = "SpreadsheetRowID"
'populate the cells with sequential numbers as long as the rows have data
  Dim k, i As Long, n As Long
120 Â Â Â With Range("a2:a" &Â Range("b" &Â Rows.Count).End(xlUp).row)
130 Â Â k = .Value
140 Â Â For i = 1 To UBound(k, 1)
150 Â Â Â Â If Len(k(i, 1)) = 0 Then
160 Â Â Â Â Â Â n = n + 1
170 Â Â Â Â Â Â k(i, 1) = n
180 Â Â Â Â End If
190 Â Â Next
200 Â Â .Value = k
210 Â Â Â End With
  'Save
220 Â Â Â xlBook.Save
230 Â Â Â xlBook.Close
240 Â Â Â xl.Quit
250 Â Â Â xl.Application.Quit
260 Â Â Â Set xl = Nothing
270 Â Â Â Set xlSheet = Nothing
You also need worksheet references in the subsequent code]
Open in new window
PS You should always make sure everything is referenced properly especially when automating Excel from another application.