Deleting A Row In Excel From VBE - vb.net

I have got some code that looks for a record in an excel file that contains the same characters as a textbox. I then need to delete that row, but I am not sure how to do this. Please could anybody help me?
Here is my code:
Dim oXL As Excel.Application
Dim oSheet As Excel.Worksheet
Dim oRng As Excel.Range
'create object and open workbook
oXL = CreateObject("Excel.application")
oXL.Workbooks.Open(CreateAdmin.FileLocation + "\DVDRental.xls")
'open worksheet
oSheet = oXL.ActiveWorkbook.Sheets("Logins")
oRng = oSheet.Range("A1:A100")
Dim blankspace As Integer = 1
Do Until oRng(blankspace, 2).value() = ""
If oRng(blankspace, 2).value() <> "" Then
blankspace = blankspace + 1
End If
Loop
Dim introw As Integer = 1
Dim user As String
Dim username As String = TextBox1.Text
If username = "" Then
MsgBox("Please Enter A User ID")
Else
Do
user = oRng(introw, 2).value()
If user = username Then
oXL.ActiveWorkbook.Save()
oXL.ActiveWorkbook.Close()
Exit Do
Else : introw = introw + 1
End If
Loop Until introw = blankspace
oRng = Nothing
oSheet = Nothing
oXL.Quit()
oXL = Nothing
TextBox1.Clear()

The following example removes rows with a first column value equal to zero. Modify it to suit your need.
As you can imagine, removing a row "repositions" all the others below, so I found it easier to work upward, rather than track the changes.
For RowDelete = Worksheets(TargetSheet).UsedRange.Rows.Count To 1 Step -1
If Cells(RowDelete, 1).Value = 0 Then
Rows(RowDelete).Delete
End If
Next RowDelete
(If this runs too slowly try ActiveSheet.EnableCalculation = False
and Application.ScreenUpdating = False before, and then again, but True after the loop.)

Related

Error 3011 when doing transferspreadsheet

Running VBA through Access.
Attempting to transfer select queries from access to excel.
If I run all the code together, then I get 3011 run-time error on the 2nd DoCmd.TransferSpreadsheet.
If I comment out all the code related to PATH1, then the 2nd DoCmd.TransferSpreadhseet runs fine.
The Microsoft Access database engine could not find the object 'TabUSR1'. Make sure the object exists and that you spell its name and the path name correctly...
I have removed a good bit of code that I feel to be irrelevant to my issue. That is why there are so many variables you do not see any code for.
Dim tempR1 As String
Dim tempR2 As String
Dim tempValue1 As String
Dim tempValue2 As String
Dim tempValue3 As String
Dim tempValue4 As String
Dim tempValue5 As String
Dim dt As Date
Dim d As String
Dim row As String
Dim rngC As Range
Dim rngU As Range
Dim fpath As String
Dim strFileExists
Dim xlappC As Excel.Application
Dim xlbookC As Excel.Workbook
Dim xlsheetC As Excel.Worksheet
Dim xlappU As Excel.Application
Dim xlbookU As Excel.Workbook
Dim xlsheetU As Excel.Worksheet
fpath = "PATH1"
strFileExists = Dir(fpath)
If strFileExists <> "" Then
'set variables for Excel
Set xlappC = CreateObject("Excel.Application")
Set xlbookC = xlappC.Workbooks.Open(fpath)
Set xlsheetC = xlbookC.Worksheets("Audit Fees Remittance")
With xlappC
.Visible = False
.DisplayAlerts = False
.Workbooks.Open fpath
'Update Raw Data Cad and CSCT tab
Set xlsheetC = xlbookC.Worksheets("Raw Data CAD and CSCT")
With xlsheetC
Set rst = CurrentDb.OpenRecordset("Weekly CAN 5 Raw Data to include csct")
If rst.RecordCount > 0 Then
tempR2 = rst.RecordCount + 1
tempR2 = .Cells(.Rows.Count, "CV").End(xlUp).Offset(tempR2).Address(False, False)
tempR1 = .Cells(.Rows.Count, "A").End(xlUp).Offset(1).Address(False, False)
Set rngC = .Range(tempR1, tempR2)
rngC.Name = "TabFA8"
DoCmd.TransferSpreadsheet acExport, 10, "PATH1", True, "TabFA8"
.Rows(2).EntireRow.Delete
rst.Close
Set rst = Nothing
Else
rst.Close
Set rst = Nothing
End If
tempValue2 = "$A$2:" & tempR2
.Range(tempValue2).EntireColumn.AutoFit
tempR1 = ""
tempR2 = ""
End With
'Remit for US
fpath = "PATH2"
strFileExists = Dir(fpath)
If strFileExists <> "" Then
'set variables for Excel
Set xlappU = CreateObject("Excel.Application")
Set xlbookU = xlappU.Workbooks.Open(fpath)
Set xlsheetU = xlbookU.Worksheets("Remittance Tab")
With xlappU
.Visible = False
.DisplayAlerts = False
.Workbooks.Open fpath
'Update INTL Remittance tab
Set xlsheetU = xlbookU.Worksheets("INTL Remittance")
With xlsheetU
Set rst = CurrentDb.OpenRecordset("Weekly US 5 Remittance Tab B DHLG and Jas")
If rst.RecordCount > 0 Then
tempR2 = rst.RecordCount + 1
tempR2 = .Cells(.Rows.Count, "V").End(xlUp).Offset(tempR2).Address(False, False)
tempR1 = .Cells(.Rows.Count, "A").End(xlUp).Offset(1).Address(False, False)
If Len(tempR1) = 3 Then
row = Right(tempR1, 2)
Else
row = Right(tempR1, 3)
End If
'set range for renaming
'this will allow TransferSpreadhseet to know where to export to on the sheet
Set rngU = .Range(tempR1, tempR2)
rngU.Name = "TabUSR2"
DoCmd.TransferSpreadsheet acExport, 10, "Weekly US 5 Remittance Tab B DHLG and Jas", "PATH2", True, "TabUSR2"
'delete row with headers
.Rows(row).EntireRow.Delete
rst.Close
Set rst = Nothing
Else
rst.Close
Set rst = Nothing
End If
End With
While I cannot exactly understand or diagnose your issue, for maintenance and readability, consider separating all Excel and Access processes. Avoid walking over same opened files with both object libraries. Therefore, consider Excel's Range.CopyFromRecordset over Access's DoCmd.TransferSpreadsheet using the very recordset you create.
...
Set rst = CurrentDb.OpenRecordset("Weekly CAN 5 Raw Data to include csct")
...
Set rngC = .Range(tempR1, tempR2)
rngC.Name = "TabFA8"
rngC.CopyFromRecordset rst
rst.Close
...
Set rst = CurrentDb.OpenRecordset("Weekly US 5 Remittance Tab B DHLG and Jas")
...
Set rngU = .Range(tempR1, tempR2)
rngU.Name = "TabUSR2"
rngU.CopyFromRecordset rst
rst.Close
Parfait's suggestion of closing the workbook then doing the TransferSpreadsheet solved my issue.

Finding Last Blank Cell Of The Excel (In Column Range H8:H38), and Updating Blank Cell In Desired Range - VB.NET

Sources:
Private Sub toEditDataOnReportCell(ByVal passedData As String)
Dim monthlyReportFilePath As String = "./Report/Example.xlsx"
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open(monthlyReportFilePath)
'Set which worksheet tobe modified
oSheet = oBook.Worksheets(1)
'This will find the lastRow in the sheet
'Dim lastRow As Integer = 7
Dim ETLastRow As Integer = oSheet.usedrange.rows.count
'This is next emptyRow in the sheet
Dim ETemptyRow As Integer = ETLastRow + 1
'edit last empty row val on column 8
Dim columnToMod As Integer = 8
oSheet.Cells(ETemptyRow, columnToMod).value = passedData
ETLastRow = oSheet.usedrange.rows.count
ETemptyRow = ETLastRow + 1
'This will not prompt the user to overwrite the excel sheet
oExcel.DisplayAlerts = False
oBook.Save()
oBook.Close()
oExcel.Quit()
TextBox12.AppendText("Sucess!!!" + vbCrLf + vbCrLf)
End Sub
Giving wrong last row, if in excel doc already have a table with formula in it.
Output Preview:
Targeting In Cell Range (H8:H38)
[1]: https://i.stack.imgur.com/D4RT5.png
But Output In Cell Range (H40:H)
[2]: https://i.stack.imgur.com/0wufs.png
Hehehe, i found the solutions,
Thanks to #StoriKnow & his answer there:
Here is my latest sources:
Private Sub toEditDataOnReportCell(ByVal passedData As String)
Dim monthlyReportFilePath As String = "./Report/Example.xlsx"
Dim oExcel As New Object
Dim oBook As New Object
Dim oSheet As New Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open(monthlyReportFilePath)
oSheet = oBook.Worksheets(1)
Try
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
sourceCol = 8 'column H has a value of 8
rowCount = oSheet.Cells(oSheet.Rows.Count, sourceCol).End(Excel.XlDirection.xlUp).Row
'for every row, find the first blank cell and select it
For currentRow = 8 To rowCount
currentRowValue = oSheet.Cells(currentRow, sourceCol).Value
If (currentRowValue Is Nothing) Or (currentRowValue = "") Then
'oSheet.Cells(currentRow, sourceCol).Select
Dim preview As String = currentRow
TextBox12.AppendText(preview + " ")
oSheet.Cells(currentRow, sourceCol).Select
oSheet.Cells(currentRow, sourceCol).value = passedData
Exit Try
End If
Next
Finally
''' DO NOTHING
End Try
''This will not prompt the user to overwrite the excel sheet
oExcel.DisplayAlerts = False
oBook.Save()
oBook.Close()
oExcel.Quit()
end Sub
Output that achived:

Internet Explorer VBA Automation Error: The object Invoked has disconnected from its clients

I'm trying to write code that will read a value from Excel, look it up in an internal web based system and store the results back in the Excel. It reads the Excel with no problem, opens Internet Explorer with no problem, but when I then try to reference what's been opened, I get the above error. The line "ie.Navigate url" works, but the next line "Set DOC = ie.Document" generates the error. Any ideas on what's causing this? Here's my code:
Public Sub getClient()
Dim xOpen As Boolean
xOpen = False
Dim row As Long
Dim xL As Excel.Application
Set xL = New Excel.Application
xL.Visible = False
Dim wb As Excel.Workbook
Dim sh As Excel.Worksheet
'Change the name as needed, out put in some facility to input it or
'process multiples...
Dim filename As String
filename = "auditLookup.xlsx"
Set wb = xL.Workbooks.Open(getPath("Audit") + filename)
xOpen = True
Set sh = wb.Sheets(1)
Dim ie As Variant
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
Dim DOC As HTMLDocument
Dim idx As Integer
Dim data As String
Dim links As Variant
Dim lnk As Variant
Dim iRow As Long
iRow = 2 'Assume headers
Dim clientName As String
Dim clientID As String
Dim nameFound As Boolean
Dim idFound As Boolean
Dim url As String
While sh.Cells(iRow, 1) <> ""
'Just in case these IDs are ever prefixed with zeroes, I'm inserting
'some random character in front, but removing it of course when
'processing.
url = "https://.../" + mid(sh.Cells(iRow, 1), 2)
ie.navigate url
Set DOC = ie.Document
'Search td until we find "Name:" then the next td will be the name.
'Then search for "P1 ID (ACES):" and the next td with be that.
Set links = DOC.getElementsByTagName("td")
clientName = ""
clientID = ""
nameFound = False
idFound = False
For Each lnk In links
data = lnk.innerText
If nameFound Then
clientName = data
ElseIf idFound Then
clientID = data
End If
If nameFound And idFound Then
Exit For
End If
If data = "Name:" Then
nameFound = True
ElseIf data = "P1 ID (ACES):" Then
idFound = True
End If
Next
sh.Cells(iRow, 2) = clientName
sh.Cells(iRow, 2) = clientID
iRow = iRow + 1
Wend
Set ie = Nothing
If xOpen Then
wb.Save
Set wb = Nothing
xL.Quit
Set xL = Nothing
Set sh = Nothing
xOpen = False
End If
Exit Sub
Changing to:
Dim ie As InternetExplorer
Set ie = New InternetExplorerMedium
...
Solved the problem. Plus I did need to add back the Do loop mentioned in the comments:
Do
DoEvents
Loop Until ie.ReadyState = READYSTATE_COMPLETE

How to Import Data Into Heavy Excel File

Goal
Import about 100+ lines of data into a worksheet. Quickly.
Current Problem
The Excel file isn't very large (not even 1MB). Although, we use this Excel file to communicate with SolidEdge which makes it very heavy.
At the moment, it takes about 60 seconds to populate the 100 lines of data. Don't get me wrong, that isn't very long. Whereas I tested it with a new and empty Excel file and it took less than 1 second to populate the data.
Code
Here's my code incase I did something stupid in there:
Private Sub PopulateExcel()
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
Dim Proceed As Boolean = False
Dim RowIndex As Integer = 2
Dim counter As Integer = 0
xlApp = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
xlWorkBooks = xlApp.Workbooks
For Each wb As Excel.Workbook In xlWorkBooks
If wb.Name.Contains("301-AAAA-00X") Then
xlWorkBook = wb
xlWorkSheets = xlWorkBook.Sheets
Exit For
End If
Next
If xlWorkSheets IsNot Nothing Then
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = "ImportSheet" Then
Proceed = True
Exit For
End If
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
End If
If Proceed Then
tspbProgress.Value = 0
tspbProgress.Maximum = dic_Vars.Count
tspbProgress.Visible = True
For Each key As KeyValuePair(Of String, String) In dic_Vars 'Contains all my the data
tsslStatus.Text = "Populating Excel: " & key.Key & " | " & key.Value
xlWorkSheet.Cells(RowIndex, 2).value = key.Key
xlWorkSheet.Cells(RowIndex, 3).value = key.Value
RowIndex += 1
IncProg()
Next
tspbProgress.Visible = False
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End If
End Sub
Private Sub ReleaseComObject(ByRef obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
End Try
End Sub
Conclusion
I was thinking about creating a new Excel file, importing the data there, and just doing a copy / paste to the real Excel file that we use.
Any suggestions?
Good thank you to Byron Wall who helped me find the answer. I now input my data using an array instead of iterating through each cell.
I create my array and populate it depending on how large my dictionary of variables is. I then create a new range using the Resize() method seen below.
Once that's done, everything is populated in an instant!
Dim arrNames(,) As String = New String(AscW(ChrW(dic_Vars.Count)), 1) {}
Dim arrValues(,) As String = New String(AscW(ChrW(dic_Vars.Count)), 1) {}
Dim i As Integer = 0
For Each key As KeyValuePair(Of String, String) In dic_Vars
arrNames(i, 0) = key.Key
arrValues(i, 0) = key.Value
i += 1
Next
If Proceed Then
Dim r As Microsoft.Office.Interop.Excel.Range = xlWorkSheet.Range("B2").Resize(arrNames.GetLength(0))
Dim r2 As Microsoft.Office.Interop.Excel.Range = xlWorkSheet.Range("C2").Resize(arrValues.GetLength(0))
r.Value2 = arrNames
r2.Value2 = arrValues
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End If

Highlighting alternating Excel Sheet Rows using VBA from an Access DB

I have been attempting to develop a routine that will highlight every nth row on a range in Excel from an Access database.
This eliminates a lot of the different code offerings on the subject since most leverage the embedded Excel functions.
The code below is a stand alone extraction from my Access VBA that I have been using for testing in hopes that I could find the correct parameter structure to make it work. As such, the code includes some Dim statements, etc that would not be required if I were embedding this macro directly as an Excel macro.
The code I have accomplishes selecting every other row but for some reason, only the first column of the intended range. I have not been able to resolve this problem and include the other columns in the formating process.
Any assistance would be much appreciated.
Sub xxx()
Dim xlbook As Excel.Workbook
Dim xlRng As Range
Dim xlFinalRange As Range
Dim intColumnCount As Integer
Dim introwcount As Integer
Dim strTable As String
Set xlbook = Excel.ThisWorkbook
strTable = "Sheet1"
introwcount = 20
intColumnCount = 14
Set xlFinalRange = Sheets(strTable).Range("A4")
xlFinalRange.Resize(1, intColumnCount).Select
Set xlRng = Sheets(strTable).Range("A4")
xlRng.Resize(1, intColumnCount).Select
intRowsBetween = 2
For i = 0 To introwcount
Set xlRng = xlRng.Offset(intRowsBetween, 0)
xlRng.Resize(1, intColumnCount).Select
Set xlFinalRange = xlbook.Application.Union(xlFinalRange, xlRng)
xlFinalRange.Resize(1, intColumnCount).Select
i = i + (intRowsBetween - 1)
Next i
xlFinalRange.Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
End Sub
The best way is to add a proper Step to your loop. Also, qualify everything properly: Range should be Excel.Range, etc. Try the following:
Sub HighlightXL()
Dim WBK As Excel.Workbook
Dim WS As Excel.Worksheet
Dim Iter As Long
Dim CombinedRng As Excel.Range, IterRng As Excel.Range
Excel.Application.Visible = True
Set WBK = Excel.Workbooks.Add 'Modify as necessary.
Set WS = WBK.Sheets("Sheet1") 'Modify as necessary.
With WS
For Iter = 1 To 22 Step 3 '1, 4, 7, 9... etc...
Set IterRng = .Cells(Iter, 1).Resize(1, 5) 'Resize to 14 in your case.
If CombinedRng Is Nothing Then
Set CombinedRng = IterRng
Else
Set CombinedRng = Union(CombinedRng, IterRng)
End If
Next Iter
End With
CombinedRng.Interior.ColorIndex = 3 'Red.
End Sub
Screenshot:
Let us know if this helps. :)
I have taken a slightly different approach in the past. Below is what I would use:
Sub ColourSheet()
Dim ApXL As Object, xlWBk As Object, xlWSh As Object, _
rng As Object, c As Object
Dim strSheet As String, strFile As String
Dim iColourRow As Integer, iRows As Integer, _
iCols As Integer, x As Integer, iStartRow As Integer
strFile = "C:\YourFolder\YourFile.xlsx"
strSheet = "SheetName"
iColourRow = 3
iRows = 30
iCols = 10
iStartRow = 2
If SmartGetObject("Excel.Application") Then
'excel open
Set ApXL = GetObject(, "Excel.Application")
Else
Set ApXL = CreateObject("Excel.Application")
End If
Set xlWBk = ApXL.Workbooks.Add
'Set xlWBk = ApXL.Workbooks.Open(strFile)
Set xlWSh = xlWBk.activesheet
'Set xlWSh = xlWBk.Worksheets(strSheet)
For x = 1 To iRows
If x Mod iColourRow = 0 Then
With xlWSh.range(xlWSh.cells(iStartRow + x - 1, 1), _
xlWSh.cells(iStartRow + x - 1, iCols)).interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
'.ThemeColor = xlThemeColorAccent1
.Color = 255
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
End If
Next x
ApXL.Visible = True
End Sub
A few notes:
Especially if you plan to distribute your database I would advise using late binding for references to Excel, if you use VBA references sooner or later someone's database will stop working and you'll reach the conclusion it is due to a missing reference. Search Late Binding and you'll see plenty on the subject. Note that with late binding you don't get the variables such as xlThemeColorAccent1, you can always get these from opening an Excel VBA instance etc.
I have used a Function call GetSmartObject which identifies if you have Excel running already, a problem I ran into quite a bit was opening additional Excel instances, hitting an error and then that instance remaining running in the background, you then need to go into Task Manager to close it.
Lastly I have just commented out the alternate workbook open where you open a designated file and set the sheet, testing it was easier to open a new workbook and use the active sheet.
Hope this helps
Function SmartGetObject(sClass As String) As Integer
Dim oTmpObject As Object
' If Server running, oTmpObject refers to that instance.
' If Server not running Error 429 is generated.
On Error Resume Next
Set oTmpObject = GetObject(, sClass)
' oTmpObject is reference to new object.
If Err = 429 Then
SmartGetObject = False
Exit Function
' Server not running, so create a new instance:
'Simon noted out: Set oTmpObject = GetObject("", sClass)
' NOTE: for Excel, you can add the next line to view the object
' oTmpObject.Visible = True
ElseIf Err > 0 Then
MsgBox Error$
SmartGetObject = False
Exit Function
End If
Set oTmpObject = Nothing
SmartGetObject = True
End Function
Credit for the above function belongs elsewhere but I've had it so long I don't know where it came from, if anyone can tell me I'll credit it correctly in future.
Option Compare Database
Option Explicit
Sub ExporttoExcel()
Dim i As Integer
Dim y As Integer
Dim varArray As Variant 'Used for obtaining the Names of the Sheets from the DB being exported
Dim varField As Variant 'Used for Naming of the Sheets being exported
Dim dbs As DAO.Database
Dim rst1 As DAO.Recordset 'DB Recordset for the Input and Output information
Dim rst2 As DAO.Recordset 'DB Recordset for the Table names to be exported and sheet names in Excel
Dim rst3 As DAO.Recordset 'DB Recordset that is reused for each Table being exported
Dim strFile As String 'Used for the name and location of the Excel file to be saved
Dim strTable As String 'Table name being exported and also used for the Sheet name
Dim strTitle As String 'Title for the Data on each sheet
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
Dim xlRunning As Boolean 'Flag to identify that Excel is running or not
Dim intColumnCount As Integer 'The number of columns on a sheet for formatting
Dim intRowCount As Integer 'The number of rows on a sheet for formatting
Dim intStartRow As Integer 'The row from which to start the highlighting process
Dim intRowsBetween As Integer 'The number of rows between highlighting
If SmartGetObject("Excel.Application") Then
Set xlApp = GetObject(, "Excel.Application") 'Excel is already open so the existing instance will be used
xlRunning = True
Else
Set xlApp = CreateObject("Excel.Application") 'Excel is not open so an instance will be created
xlRunning = False
End If
Set xlBook = xlApp.Workbooks.Add
xlApp.Visible = True
xlApp.DisplayAlerts = False
Set dbs = CurrentDb
'Retrieve Study Location and Name for Import to Database
Set rst1 = dbs.OpenRecordset("StudyTarget")
strFile = rst1!OutputFile
' Removed VBA for File Name & Save Path Information
With xlBook
Set rst2 = dbs.OpenRecordset("ExportTableGroup", dbOpenSnapshot)
' Removed VBA for Excel Naming information from DB
For y = 0 To rst2.RecordCount - 1
strTable = varArray(y, 1)
strTitle = varArray(y, 2)
Set rst3 = dbs.OpenRecordset(strTable, dbOpenTable)
.Sheets.Add after:=Sheets(Sheets.Count)
.Sheets(Sheets.Count).Name = strTable
Set xlSheet = .ActiveSheet
'COPY the Access Table Data to the Named Worksheet
xlSheet.Cells(2, 1).CopyFromRecordset rst3
'Select every X number of rows between sheet Data Rows on Worksheet to highlight
intRowsBetween = 2
intStartRow = 4
For i = 0 To intRowCount Step intRowsBetween
If xlSheet.Cells(intStartRow + i, 1) = "" Then
Exit For
End If
With xlSheet.Range(xlSheet.Cells(intStartRow + i, 1), _
xlSheet.Cells(intStartRow + i, intColumnCount)).Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = RGB(186, 186, 186)
.TintAndShade = 0.6
.PatternTintAndShade = 0
End With
Next i 'Next Row
Next 'Next Table
.Sheets("sheet1").Delete
.Sheets(1).Select 'Go to first sheet of workbook
End With
Export_to_Excel_Exit:
rst1.Close
rst2.Close
rst3.Close
xlApp.ActiveWorkbook.Save
xlBook.Close
If xlRunning Then 'Check to see if used an existing instance of Excel via SmartGetObject
Else
xlApp.Quit
Set xlApp = Nothing
End If
Set xlBook = Nothing
Set rst1 = Nothing
Set rst2 = Nothing
Set rst3 = Nothing
Set dbs = Nothing
Exit Sub