I am trying to remove the duplicates in excel via the following code:
Set rng = Range("A1", Range("A1").SpecialCells(xlLastCell))
rng.removeduplicates Columns:=8, Header:=xlYes
This method seems to work half of the time. Sometimes it works, sometimes it gives me the following error:
Searching on run-time error 1004 gives me the info that there shouldn't be strings, with more than 911 chars, which is not the case. When running the code multiple times on the same excel file, it goes well around 50 percent of the time.
I am running the code in ms access 2007, but all my references are switched on. The question is ofcourse, how to solve this, but any other, better way to easily remove my duplicates will be appreciated as well. Thank you.
EDIT: Full code:
Const xlLastCell As Long = 11
Const xlYes As Long = 1
Public Function formatreports(FileName As String) As String
Dim xl As Excel.Application
Dim xlwb As Excel.Workbook
Dim xlsh As Excel.Worksheet
Dim rng As Range
Dim newname As String
Set xl = CreateObject("Excel.Application")
xl.DisplayAlerts = False
xl.Visible = False
Set xlwb = xl.Workbooks.Open(FileName)
Set xlsh = xlwb.Worksheets(1)
'its MFR0004; This is solely for import reasons
xlsh.Rows("1:4").Delete
xlsh.Rows("2").Delete
xlsh.Columns("A:B").Delete
xlsh.Columns("B").Delete
'This as well
xlsh.Range("J1") = "Total Weight"
xlsh.Range("L1") = "Net Weight"
xlsh.Range("O1") = "Gross Weight"
xlsh.Range("AA1") = "Delivery Date"
Set rng = xlsh.Range("A1", Range("A1").SpecialCells(xlLastCell))
rng.removeduplicates Columns:=8, Header:=xlYes
newname = Left(FileName, Len(FileName) - 4) & ".XLSX"
xlwb.SaveAs newname, FileFormat:=51
formatreports = newname
xlwb.Save
xlwb.Close
xl.Quit
Set xl = Nothing
End Function
The problem is that your cells are not fully qualified.
You need to try something like this
' change sheet1 to the relevant worksheet
With ThisWorkbook.Sheets("Sheet1")
Set rng = .Range("A1", .Range("A1").SpecialCells(xlLastCell))
rng.RemoveDuplicates Columns:=8, Header:=xlYes
End With
On A side note: Since you are saying that you are working from Access and this code works sometime that means you are maybe using Early Binding. If you are not then you will have to add these to the top of your code
Const xlLastCell As Long = 11
Const xlYes As Long = 1
Related
I have made 2 functions "WrongEntries" & "Duplicates". When I run it individually it runs perfectly. But when I run it one after the other it reflects Method 'range' of object '_global' failed.
I am not sure is it because of the objects still in the memory of the previous run function but i did use different objects & variable in both functions still same error was there. Also tried putting objects as nothing.
Stange part is if I shuffle their run-first one always runs perfectly doesn't matter which one it is.
Function WrongEntries()
Dim dbs As Database Dim lRow As Long Dim lCol As Long Dim rg As Range
Set dbs = CurrentDb
Set rgQuery = dbs.OpenRecordset("5G High Cycle Times")
Set excelApp = CreateObject("Excel.application", "")
excelApp.Visible = True
Set targetWorkbook = excelApp.Workbooks.Open("\5G Wrong
Entries_Blank.xlsx")
targetWorkbook.Worksheets("Cycle Times >5
weeks").Range("A2").CopyFromRecordset rgQuery
targetWorkbook.Worksheets("Cycle Times >5 weeks").Activate
lRow = Range("b" & Rows.Count).End(xlUp).Row
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
excelApp.Quit
Set excelApp = Nothing
End Function
''' Problems is when I run second one together with first'''
Function Duplicates()
Dim dbs As Database Dim lastRw As Long Dim lastCl As Long Dim rnge As
Range Dim wks As Worksheet
Set excelApp = CreateObject("Excel.application", "")
excelApp.Visible = True
Set dbs = CurrentDb
Set rdQuery = dbs.OpenRecordset("5G Duplicates Check")
Set excelApp = CreateObject("Excel.application", "")
excelApp.Visible = True
Set targetWorkbook = excelApp.Workbooks.Open("\5G Duplicates_Blank.xlsx")
Set wks = targetWorkbook.Worksheets("Duplicates")
targetWorkbook.Worksheets("Duplicates").Range("A2").CopyFromRecordset
rdQuery
Here the error is reflecting while calculating last row count
lastRw = wks.Range("a" & Rows.Count).End(xlUp).Row
lastCl = wks.Cells(1, Columns.Count).End(xlToLeft).Column
End Function
You close the application:
excelApp.Quit
Set excelApp = Nothing
leaving the workbook and all objects orphaned. So:
targetWorkbook.Close
Set targetWorkbook = Nothing
excelApp.Quit
Set excelApp = Nothing
Further: Always use specific objects. Not
Range("b" & Rows.Count).End(xlUp).Row
Cells(1, Columns.Count).End(xlToLeft).Column
but:
Set range = SomeWorksheet.Range ...
set cell = SomeWorksheet.Cells ...
and terminate these as the first:
Set cell = Nothing
Set range = Nothing
Set wks = nothing
targetWorkbook.Close
Set targetWorkbook = Nothing
excelApp.Quit
Set excelApp = Nothing
Happy Anniversary and all the best for this community
I am trying to learn the use of DoCmd.TransferSpreadsheet to export queries and charts to Excel
In my Database, I have two forms to export in each one a query to Excel and create a Chart
In each Form, the user selects a value in a textbox and an image is displayed on the Form
In Form frm_createxlstacked, the user picks two dates and click a command button to export the query to Excel and creates an xlClustered Chart. This VBA code works fine.
This is VBA code for createxlstacked
Private Sub cmbexpqry_stacked_Click()
Dim wb As Object
Dim xl As Object
Dim sExcelWB As String
Dim ws As Worksheet
Dim r As Range
Dim ch As Object ''Excel.Chart
Dim mychart As ChartObject
Dim myMax, myMin As Double
Dim qry_createxlstacked As Object
Dim fullPhotoPath As String
If IsNull(Me.cbxclstacked.Value) Then Exit Sub
Dim wb As Object, xl As Object, ch As Object, mychart As ChartObject
Dim fullPhotoPath As String
fullPhotoPath = Add_PlotMap(Form_frm_createxlstacked.cbxclstacked.Value)
Set xl = CreateObject("excel.application")
On Error Resume Next
Kill TrailingSlash(CurrentProject.Path) & Form_frm_createxlstacked.cbxxlstacked.Value & "qry_createxlstacked.xlsx"
Err.Clear
On Error GoTo 0
sExcelWB = TrailingSlash(CurrentProject.Path) & "qry_createxlstacked.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "qry_createxlstacked.xlsx", sExcelWB, True
Set wb = xl.Workbooks.Open(sExcelWB)
Set ws = wb.Sheets("qry_createxlstacked.xlsx")
Set ch = ws.Shapes.AddChart.Chart
Set mychart = ws.ChartObjects("Chart 1")
ws.Shapes.AddPicture fullPhotoPath, msoFalse, msoCTrue, r.Left, r.Top, 500, 250
With ch
.ChartType = xlColumnClustered
.SeriesCollection(2).AxisGroup = 2
.SeriesCollection(2).ChartType = xlLineMarkers
.ChartGroups(1).GapWidth = 69
.ChartArea.Height = 250
.ChartArea.Width = 550
End with
wb.Save
xl.Visible = True
xl.UserControl = True
Set ws = Nothing
Set wb = Nothing
End Sub
In Form frm_creategannt, the user picks two dates and click a command button to export query to Excel and creates an xlClustered Chart, but, VBA displays:
Run-time error '3011'. The Microsoft Office Access database engine could not find the object 'qry_creategantt.xlsx'. Make sure that the object exists and that you...
This is VBA code
Private Sub cmbexpqry_gantt_Click()
If IsNull(Me.cmbexpqry_gantt) Then Exit Sub
Dim wb As Object
Dim xl As Object
Dim sExcelWB As String
Dim ws As Worksheet
Dim r As Range
Dim ch As Object ''Excel.Chart
Dim mychart As ChartObject
Dim qry_creategantt As Object
Dim fullPhotoPath As String
fullPhotoPath = Add_PlotMap(Form_frm_creategantt.cbxcreategantt.Value)
Set xl = CreateObject("excel.application")
On Error Resume Next
Kill TrailingSlash(CurrentProject.Path) & Form_frm_creategantt.cbxcreategantt.Value & "qry_creategantt.xlsx"
Err.Clear
On Error GoTo 0
sExcelWB = TrailingSlash(CurrentProject.Path) & "qry_creategantt.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "qry_creategantt.xlsx", sExcelWB, True
Set wb = xl.Workbooks.Open(sExcelWB)
Set ws = wb.Sheets("qry_creategantt.xlsx")
Set ch = ws.Shapes.AddChart.Chart
Set mychart = ws.ChartObjects("Chart 1")
ws.Shapes.AddPicture fullPhotoPath, msoFalse, msoCTrue, r.Left, r.Top, 500, 250
With ch
.ChartType = xlBarStacked
End With
wb.Save
xl.Visible = True
xl.UserControl = True
Set ws = Nothing
Set wb = Nothing
End Sub
The error is '3011' occurs in this line:
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, qry_creargantt.xlsx", sExcelWB, True
I compared one by one each line of codes.
Also, I checked the Queries for each form.
I need to fix Run-time error '3011' to start testing VBA code to create Gantt Chart
In my opinion, I found no error, but I am stuck
I appreciate your reply, suggestion and effort in code with error.
If the error is occuring on the DoCmd.TransferSpreadsheet line as you indicate, then the error is very clear.
You have told Microsoft Access to run the query named qry_creategantt.xlsx (in order to export that data to Excel) and that query does not exist in your database.
Check the spelling of the Query in the Queries list, and in your code. In your question above, where you restate that line of code as where the error occurs, you spelled the query name differently: qry_creargantt.xlsx. Which spelling is correct? That may be your problem.
It's not possible to call a query ".anything" the . is an illegal character in an access query name.
So carefully check the name of your query you are referring to. Because it isn't qry_creategantt.xlsx
I am using someone else's code because this is an old file other people are using, I want to update it to make it more efficient but I need a little help. Below is the vba operation. What I need is it to get the information but delete everything but a certain word which changes every time the operation is run. I could use regex and objRE.Pattern = "|" but the word changes depending on the status.
HTML:
<span onmouseover="ShowText('Message','blahblah'); return true;"
onmouseout="HideText('Message'); return true;"
href="javascript:ShowText('Message')">---(PSA)---</span>
</font><a href='?srn=numbers12131131'target='_self'><font color='#6666FF'
size='3'>numbers123232343</font></a><font size='3'>----Installed----MUM
Indication:In Scope-<font color='#00CC00'>PASS WITH WARNING</font>--- (20181018)
</td><tr></table> </b><br>
<table class="OrderForm" width="1000"> '
I just want the Installed status in my excel sheet.
VBA code that needs work:
Sub GetComment()
Dim book As Workbook
Dim sheet As Worksheet
Dim row As Integer
Dim SRN As String
Dim whttp As Object
Set book = ThisWorkbook
Set sheet = book.Worksheets("CMT Data")
Set whttp = CreateObject("WinHTTP.WinHTTPrequest.5.1")
row = 2
SRN = sheet.Cells(row, 1)
Do While SRN <> ""
Debug.Print SRN
whttp.Open "GET", "www.websitedatgoeshere.com" & SRN, False
whttp.SetRequestHeader "Cookie", "mycookiefromwebsite;"
whttp.send
Debug.Print whttp.responseText
sheet.Cells(row, 2) = whttp.responseText
row = row + 1
SRN = sheet.Cells(row, 1)
Loop
Set whttp = Nothing
End Sub
This is based on if, and only if, the word is always between "----" and "----", and that it is the first occurrence in the response. If not the first you can adjust the index 1 as required.
Debug.Print Split(Split(whttp.responseText, "----")(1), "----")(0)
sheet.Cells(row, 2) = Split(Split(whttp.responseText, "----")(1), "----")(0)
So I have a query in access that I want to send back to excel. While using the export wizard is fine and dandy I want to add more automation to the exporting process. So far I am working on code so during the export the final excel sheet will have some formatting. As far as basic formatting I am fine, I found many resources to help me with this.
My problem is that I want to set up conditional formatting so that if a specific column(G) has a value, then the whole row is highlighted. I am a bit lost on how to set up conditional formatting for Excel through vba code in Access
Here is what I have
Dim appExcel As Variant
Dim MyStr As String
Dim rng As Excel.Range
' Creates Excel object and Adds a Workbook to it
Set appExcel = CreateObject("Excel.application")
appExcel.Visible = False
appExcel.Workbooks.Add
Set wksNew = appExcel.Worksheets("Sheet1")
appExcel.Visible = True
' The first thing I do to the worksheet is to set the font.
' Not all are required, but I included them as examples.
With appExcel
.Cells.Font.Name = "Calbri"
.Cells.Font.Size = 11
.Cells.NumberFormat = "#" 'all set to Text Fields
' My first row will contain column names, so I want to freeze it
.Rows("2:2").Select
.ActiveWindow.FreezePanes = True
' ... and I want the header row to be bold
.Rows("1:1").Font.Bold = True
.Rows("1:1").Font.ColorIndex = 1
.Rows("1:1").Interior.ColorIndex = 15
' Adds conditional formatting based on Values in the G column
rng = .Range("A2:J20").Select
rng.FormatConditions.Add Type:=xlExpression, Formula1:="=NOT($G2 = 0)"
rng.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With appExcel.Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
End With
End With
Currently the code executes until my conditional formatting block and then it tells me that the Object Variable or With block is not set.
I checked that the following code runs until the end:
Dim appExcel As Variant
Dim MyStr As String
Dim rng As Excel.Range
Dim wksNew
' Creates Excel object and Adds a Workbook to it
Set appExcel = CreateObject("Excel.application")
appExcel.Visible = False
appExcel.Workbooks.Add
' Set wksNew = appExcel.Worksheets("Sheet1")
Set wksNew = appExcel.Worksheets(1)
appExcel.Visible = True
' The first thing I do to the worksheet is to set the font.
' Not all are required, but I included them as examples.
With appExcel
.Cells.Font.Name = "Calbri"
.Cells.Font.Size = 11
.Cells.NumberFormat = "#" 'all set to Text Fields
' My first row will contain column names, so I want to freeze it
.Rows("2:2").Select
.ActiveWindow.FreezePanes = True
' ... and I want the header row to be bold
.Rows("1:1").Font.Bold = True
.Rows("1:1").Font.ColorIndex = 1
.Rows("1:1").Interior.ColorIndex = 15
' Adds conditional formatting based on Values in the G column
Set rng = .Range("A2:J20")
rng.Select
rng.FormatConditions.Add Type:=xlExpression, Formula1:="=NOT($G2 = 0)"
rng.FormatConditions(rng.FormatConditions.Count).SetFirstPriority
With rng.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
End With
End With
Good luck.
I have created a data base that comes in an installer that runs as an epos system.
On installing it on other computers, I get a large number of errors all saying that something is missing. the file runs perfectly on my computer, but the errors stop anything from working on other computers....
the errors are as follows. each has its own popup box.
broken reference to excel.exe version 1.7 or missing.
acwztool.accde missing
npctrl.dll v4.1 missing
contactpicker.dll v1.0 missing
cddbcontolwinamp.dll v1.0 missing
cddbmusicidwinamp.dll v1.0 missing
colleagueimport.dll v1.0 missing
srstsh64.dll missing
I feel like this may because I altered the module vba library referencing so that I could run a vba code that uses excel, unfortunatly i have forgotten which librarys i have added
if it helps, the code that I added which required new references is below
Public Sub SalesImage_Click()
Dim rst As ADODB.Recordset
' Excel object variables
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim xlChart As Excel.Chart
Dim i As Integer
On Error GoTo HandleErr
' excel aplication created
Set xlApp = New Excel.Application
' workbook created
Set xlBook = xlApp.Workbooks.Add
' set so only one worksheet exists
xlApp.DisplayAlerts = False
For i = xlBook.Worksheets.Count To 2 Step -1
xlBook.Worksheets(i).Delete
Next i
xlApp.DisplayAlerts = True
' reference the first worksheet
Set xlSheet = xlBook.ActiveSheet
' naming the worksheet
xlSheet.name = conSheetName
' recordset creation
Set rst = New ADODB.Recordset
rst.Open _
Source:=conQuery, _
ActiveConnection:=CurrentProject.Connection
With xlSheet
' the field names are imported into excel and bolded
With .Cells(1, 1)
.Value = rst.Fields(0).name
.Font.Bold = True
End With
With .Cells(1, 2)
.Value = rst.Fields(1).name
.Font.Bold = True
End With
' Copy all the data from the recordset into the spreadsheet.
.Range("A2").CopyFromRecordset rst
' Format the data the numbering system has been extended to encompas up to 9,999,999 sales to cover all posibilities of sales since the last stock take
.Columns(1).AutoFit
With .Columns(2)
.NumberFormat = "#,###,###"
.AutoFit
End With
End With
' Create the chart.
Set xlChart = xlApp.Charts.Add
With xlChart
.ChartType = xl3DBarClustered
.SetSourceData xlSheet.Cells(1, 1).CurrentRegion
.PlotBy = xlColumns
.Location _
Where:=xlLocationAsObject, _
name:=conSheetName
End With
'the reference must be regotten as it is lost
With xlBook.ActiveChart
.HasTitle = True
.HasLegend = False
With .ChartTitle
.Characters.Text = conSheetName & " Chart"
.Font.Size = 16
.Shadow = True
.Border.LineStyle = xlSolid
End With
With .ChartGroups(1)
.GapWidth = 20
.VaryByCategories = True
End With
.Axes(xlCategory).TickLabels.Font.Size = 8
.Axes(xlCategoryScale).TickLabels.Font.Size = 8
End With
With xlBook.ActiveChart
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Product"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Sales"
End With
'format the size and possition of the chart
With xlBook.ActiveChart
.Parent.Width = 800
.Parent.Height = 550
.Parent.Left = 0
.Parent.Top = 0
End With
'this displays the chart in excel. excel must be closed by the user to return to the till system
xlApp.Visible = True
ExitHere:
On Error Resume Next
'this cleans the excel file
rst.Close
Set rst = Nothing
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing
Exit Sub
HandleErr:
MsgBox Err & ": " & Err.Description, , "There has been an error!"
Resume ExitHere
End Sub
Deployment should be less troublesome if you remove your project's Excel reference and use late binding for Excel objects.
A downside is you lose the benefit of Intellisense during development with late binding. However it's very easy to switch between early binding during development and late binding for production. Simply change the value of a compiler constant.
In the module's Declarations section ...
#Const DevStatus = "PROD" 'PROD or DEV
Then within the body of a procedure ...
#If DevStatus = "DEV" Then
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Set xlApp = New Excel.Application
#Else ' assume PROD (actually anything other than DEV)
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
Set xlApp = CreateObject("Excel.Application")
#End If
With late binding your code will need to use the values of Excel constants rather than the constants names. Or you can define the named constants in the #Else block for production use then continue to use them by name in your code.
I don't know what all those other reference are. Suggest you take a copy of your project, remove all those references and see what happens when you run Debug->Compile from the VB Editor's main menu. Leave any unneeded references unchecked. And try late binding for the rest. I use only 3 references in production versions of Access applications: VBA; Access; and DAO.