Check if unique identifier is present in "new data", if not, add entries to "historical data" sheet? - vba

I've got data with a unique ID number in one column. This is pasted into a "Raw Data" sheet by the user.
Then, I've got macros that manipulate the "Raw Data", including archiving some of it on a "archival" worksheet which includes the ID numbers.
I want to run a check to see if there are any "new" ID numbers in the "Raw Data", and if so add a new row with some of the data including the ID number to the "archival" sheet.
I've googled and checked here. It looks like I want to use a Collection? Never encountered this so far, not sure where to start.
Sorry that this isn't the most well structured question, and that it doesn't include any code. Not sure how to get started.
It should be noted that this reconciliation only needs to go one way -- I don't need to delete "old" unique IDs from the "archival" sheet.
Thanks!

If you specifically want to use collections, over Range.Find, you can do so like this.
Although handling errors this way in VBA is best to avoid most times, for iterating over collections, it can result in faster and often less verbose code.
I have used named ranges for a Rawdata and Archive worksheet tabs, so you will need to adapt this to your own situation. What this does is use collections to store unique items already in Archive, and compare these against items in Rawdata - when a new (unique) item is found in Rawdata that is not already in Archive, it is added to the sheet (and collection).
Sub IDcollection()
Dim IDcoll As New Collection
Dim cells, Rng, Rng_a As Range
Set Rng = Worksheets("Rawdata").Range("IDRANGE")
Set Rng_a = Worksheets("Archive").Range("IDRANGE_A")
'IDRANGE looks like string IDs 'abc', 'ab1',etc
'get unique IDs already in ARCH sheet via named range
On Error Resume Next 'includes only unique items
For Each cells In Rng_a.cells
IDcoll.Add cells.Text, cells.Text
'use the IDs as the KEY in the VBA Collection
Next cells
'check for unique items not in Archive, but in Rawdata (i.e. new items)
On Error Resume Next
For Each cells In Rng
IDcoll.Item cells.Text
If Err.Number <> 0 Then
IDcoll.Add cells.Text, cells.Text
LastRow = Rng_a.Rows(Rows.Count).End(xlUp).Row + 1
Rng_a(LastRow).Value = cells.Text
Err.Clear
End If
Next
End Sub
Just stick this in a module in your VBA for your worksheet, set up some named ranges as above, populated with dummy data.

Related

VBA Table in Merged Letter

I have an Excel Sheet with a lot of customer Data. All customers have common data (address, name etc.) that I implemented as simple mergefields. Some Customers have multiple Datasets that should be added as a Table at the end of the merged letter.
To find the Data from my excel Sheet I already came up with the following code.
noInt is the number of customers while noData is the number of different datasets (all customers together, some multiples). exWb is the excel workbook my data comes from and the data I want to display in the table lays in columns 5 to 9.
For i = 2 To noInt
For k = 2 To noData
If exWb.Sheets("Table1").Cells(k, 1) = exWb.Sheets("Table2").Cells(i, 1) Then
For j = 5 To 9
Insert into Table exWb.Sheets("Table1").Cells(k, j)
Next j
End If
Next k
Next i
Now my questions:
How can I insert this data into a newly created table after the placeholder "insert_table_here"?
How can I make sure that for every letterin the mail merge series there is only the data of the customer the letter is about included in this table?
To find a solution to this, I already thought about if there was maybe a function that gives the current "Mail Merge Number". In that case I could compare the field (MailMergeNumber, 1) with (k,1) to only show the results that include the current customer.
Example to make it more understandable:
Dear Mr A,
...
Table of items Mr. A bought
-End of document-
Dear Mr. B,
...
Table of items Mr. B bought
-End of document-
And so on...
If you're creating Word documents from a template (that's generally the easiest way I've found to do it), you can add a table to the template document with the header rows you need, and 1 blank row for the data. Then, after populating the basic mergefields, you could loop through the current customer fields, adding new rows to the Word table as you went. Something like this:
Dim exWs as Excel.Worksheet
Dim CurrentCustomerFirstCell as Excel.Range
Dim CurrentCustomerActiveCell as Excel.Range
Dim EmpRowOffset as integer
Dim wdDoc as Word.Document
Dim wdTable as Word.Table, wdCell as Word.Cell
' set up your existing references, including (I assume) to the Word document you're updating
set exWs = exWb.Sheets("Table1")
' initialize row for current employee
CurrentCustomerFirstCell = exWs.Cells(2,1)
do while CurrentCustomerFirstCell.Row <= noData ' consider renaming noData to somthing like "numberOfRows"
' populate basic mergefields
wdDoc.Fields(1).Result.Text = CurrentCustomerFirstCell.Value
' etc.
' populate table in Word document
set wdTable = wdDoc.Tables(1)
EmpRowOffset = 0
set CurrentCustomerActiveCell = CurrentCustomerFirstCell.Offset(Rowoffset:=EmpRowOffset)
set wdTable = wdDoc.Tables(1)
do while CurrentCustomerActiveCell.Value = CurrentCustomerFirstCell.Value
' this code would update the first "data" row in the existing Word table
' to the 6th column of the active employee row
set wdCell = wdTable.Cell(Row:=2 + EmpRowOffset, Column:=1)
wdCell.Range.Text = _
CurrentCustomerActiveCell.Offset(columnoffset:=5).Value
wdTable.Rows.Add
EmpRowOffset = EmpRowOffset + 1
set CurrentCustomerActiveCell = CurrentCustomerFirstCell.Offset(RowOffset:=EmpRowOffset)
Loop
' now that we're finished processing the employee, update CurrentCustomerFirstCell
set CurrentCustomerFirstCell = CurrentCustomerActiveCell
loop
You can use Word's Catalogue/Directory Mailmerge facility for this (the terminology depends on the Word version). To see how to do so with any mailmerge data source supported by Word, check out my Microsoft Word Catalogue/Directory Mailmerge Tutorial at:
http://www.msofficeforums.com/mail-merge/38721-microsoft-word-catalogue-directory-mailmerge-tutorial.html
or:
http://www.gmayor.com/Zips/Catalogue%20Mailmerge.zip
The tutorial covers everything from list creation to the insertion & calculation of values in multi-record tables in letters. Do read the tutorial before trying to use the mailmerge document included with it.
Depending on what you're trying to achieve, the field coding for this can be complex. However, since the tutorial document includes working field codes for all of its examples, most of the hard work has already been done for you - you should be able to do little more than copy/paste the relevant field codes into your own mailmerge main document, substitute/insert your own field names and adjust the formatting to get the results you desire. For some worked examples, see the attachments to the posts at:
http://www.msofficeforums.com/mail-merge/9180-mail-merge-duplicate-names-but-different-dollar.html#post23345
http://www.msofficeforums.com/mail-merge/11436-access-word-creating-list-multiple-records.html#post30327
Another option would be to use a DATABASE field in a normal ‘letter’ mailmerge main document and a macro to drive the process. An outline of this approach can be found at:
http://answers.microsoft.com/en-us/office/forum/office_2010-word/many-to-one-email-merge-using-tables/8bce1798-fbe8-41f9-a121-1996c14dca5d
Conversely, if you're using a relational database or, Excel workbook with a separate table with just a single instance of each of the grouping criteria, a DATABASE field in a normal ‘letter’ mailmerge main document could be used without the need for a macro. An outline of this approach can be found at:
https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-mso_winother-mso_2010/mail-merge-to-a-word-table-on-a-single-page/4edb4654-27e0-47d2-bd5f-8642e46fa103
For a working example, see:
http://www.msofficeforums.com/mail-merge/37844-mail-merge-using-one-excel-file-multiple.html
Alternatively, you may want to try one of the Many-to-One Mail Merge add-ins, from:
Graham Mayor at http://www.gmayor.com/ManyToOne.htm; or
Doug Robbins at https://onedrive.live.com/?cid=5AEDCB43615E886B&id=5AEDCB43615E886B!566

How to search multiple columns for unique text to input those unique rows into other sheet

I am not sure if my question is going to be regarding a macro in VBA or a VLOOKUP type of thing but I'll try my best to explain both.
I am trying to make a time sheet for people to enter their time spent working on various projects. It works well but I am trying to add a feature to separate the time spent at regular pay, overtime pay, or double time pay.
There are three sheets named Time Log, Project List, and Timesheet.
This is an image from Time Log:
Employees enter the project name and project number and task is retrieved from Project List using VLOOKUP and then the employee enters the type of payment they receive for that work. Throughout the week, an employee may enter multiples of the same entries.
At the end of the week, they'll go to Timesheet and press a button I have attached to a macro which will retrieve the unique values from all the entries in the Time Log.
This is an image from Timesheet:
As you can see, I have made it work to find the unique project names but now I have run into an issue with the pay type that is entered. I am not sure how to have it draw a new entry for each unique project name and unique type.
Ideally, it would come out like this:
So what I have so far is my macro to search the Time Log for unique project names and put them into Timesheet:
Sub Input_Project_Names()
'
' Input_Project_Names Macro
'
' Clear Project Names
Worksheets("Timesheet").Range("A4:A50").ClearContents
'Advanced Filter from Time Log to Timesheet
Sheets("Time Log").Range("A1").CurrentRegion.AdvancedFilter _
Action:=xlFilterCopy, _
CriteriaRange:=Sheets("Project List").Range("H1:H2"), _
CopyToRange:=ActiveSheet.Range("A3:A52"), _
Unique:=True
End Sub
So this is where I am stuck... How do I modify the macro so that it looks for unique project names & types? And if I'm unable to do this, is there a way to use VLOOKUP or similar to do what I'm aiming for?
Big thanks for all help!
you could use SortedList object:
Option Explicit
Sub main()
Dim sortedList As Object
Set sortedList = CreateObject("System.Collections.SortedList")
Dim cell As Range
With Worksheets("Time Log") 'reference "Time Log" worksheet
For Each cell In .Range("A2", .cells(.Rows.Count, 1).End(xlUp)) 'loop thorugh referenced sheet column A cells from row 2 down to last not empty one
sortedList(cell.Value & "," & cell.Offset(, 3).Value) = cell.Resize(, 4).Value 'add current record to SortedList assigning "Project Name, Type" as ist key : it will do nothing if there's already a record with the same "Project Name" & "Type" key
Next
End With
Dim i As Long
With Worksheets("Time Sheet") ''reference "Time Sheet" worksheet
For i = 0 To sortedList.Count - 1 'loop through Sorted List object items
.cells(.Rows.Count, 1).End(xlUp).Offset(1).Resize(, 4).Value = sortedList.GetByIndex(i) 'write referenced sheet currently first empty row with current Sorted List item
Next
End With
End Sub

Embedded "IF" formula breaks occasionally, VBA alternative?

I have a very large embedded IF formula that appears to occasionally break for no reason. Opening and closing the page a few times eventually gets it working again. I am wondering if there is a VBA alternative for it. Here is the IF formula I am running.
=IF(ISNUMBER(SEARCH("76210",E125)),"_012_00762_10",IF(ISNUMBER(SEARCH("76220",E125)),"_012_00762_20",IF(ISNUMBER(SEARCH("76900",E125)),"_012_00769_00",IF(ISNUMBER(SEARCH("76901",E125)),"_012_00769_01",IF(ISNUMBER(SEARCH("85702",E125)),"_012_00857_02",IF(ISNUMBER(SEARCH("85710",E125)),"_012_00857_10",IF(ISNUMBER(SEARCH("100800",E125)),"_012_01008_00",IF(ISNUMBER(SEARCH("100900",E125)),"_012_01009_00",IF(ISNUMBER(SEARCH("123100",E125)),"_012_01231_00",IF(ISNUMBER(SEARCH("124600",E125)),"_012_01246_00",IF(ISNUMBER(SEARCH("124601",E125)),"_012_01246_01",IF(ISNUMBER(SEARCH("124640",E125)),"_012_01246_40",IF(ISNUMBER(SEARCH("124641",E125)),"_012_01246_41",IF(ISNUMBER(SEARCH("142301",E125)),"_012_01423_01",IF(ISNUMBER(SEARCH("158801",E125)),"_012_01588_01",IF(ISNUMBER(SEARCH("158900",E125)),"_012_01589_00",IF(ISNUMBER(SEARCH("159203",E125)),"_012_01592_03",IF(ISNUMBER(SEARCH("159303",E125)),"_012_01593_03",IF(ISNUMBER(SEARCH("159401",E125)),"_012_01594_01",IF(ISNUMBER(SEARCH("159410",E125)),"_012_01594_10",IF(ISNUMBER(SEARCH("159420",E125)),"_012_01594_20",IF(ISNUMBER(SEARCH("159501",E125)),"_012_01595_01",IF(ISNUMBER(SEARCH("169000",E125)),"_012_01690_00",IF(ISNUMBER(SEARCH("186900",E125)),"_012_01869_00",IF(ISNUMBER(SEARCH("213200",E125)),"_012_02132_00",IF(ISNUMBER(SEARCH("213300",E125)),"_012_02133_00",IF(ISNUMBER(SEARCH("215400",E125)),"_012_02154_00",IF(ISNUMBER(SEARCH("220100",E125)),"_012_02201_00",IF(ISNUMBER(SEARCH("223800",E125)),"_012_02238_00",IF(ISNUMBER(SEARCH("225600",E125)),"_012_02256_00",IF(ISNUMBER(SEARCH("230700",E125)),"_012_02307_00",IF(ISNUMBER(SEARCH("230701",E125)),"_012_02307_01",IF(ISNUMBER(SEARCH("231800",E125)),"_012_02318_00",IF(ISNUMBER(SEARCH("235000",E125)),"_012_02350_00",IF(ISNUMBER(SEARCH("235020",E125)),"_012_02350_20",IF(ISNUMBER(SEARCH("242000",E125)),"_012_02420_00",IF(ISNUMBER(SEARCH("246400",E125)),"_012_02464_00",IF(ISNUMBER(SEARCH("292900",E125)),"_012_02929_00",""))))))))))))))))))))))))))))))))))))))
Basically it is built so a serial number is scanned and it populates a cell for the users who use this sheet with its results from the search. I am already running one macro in this sheet as well. Here is that...
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Set rng = Intersect(Range("A2:A500, J2:J500"), Target) ' define range of interest
If Not rng Is Nothing Then ' check it's not "nothing"
If WorksheetFunction.CountA(rng) = rng.Count Then 'check for all of its cells being not empty
On Error GoTo safe_exit 'add error control
Application.EnableEvents = False 'don't do anything until you know something has to be done
rng.Offset(, 1).Value = Date 'write Date next to all relevant changed cells
End If
End If
safe_exit:
Application.EnableEvents = True
End Sub
Maybe there is a better way to build this search using a formula that isn't using embedded IF statements, but i couldn't think of another way to do it. Thanks in advance.
This may be what you're looking for:
=IF(ISNA(MATCH(1,IF(ISERR(SEARCH($A$5:$A$42,$E$125)),0,1),0)),"",INDEX($B$5:$B$42,MATCH(1,IF(ISERR(SEARCH($A$5:$A$42,$E$125)),0,1),0)))
entered as an array formula (CTRL-SHIFT-ENTER).
Here $A$5:$A$42 contains 76210, 76220, ... , 292900 (entered as text, not numbers); and $B$5:$B$42 contains _012_00762_10, _012_00762_20, ... , _012_02929_00.
Hope that helps.
Any time you have to go more than 2 deep on an IF you may want to rethink the usage.
What you can do is build a table from your values. Then reference that table as part of your lookup. Assuming your list of value is in range D8:E45 you could use the formula =VLOOKUP(E125,$D$8:$E$45,2).
The beginning of your table would look like what's seen below. The input result cell is referencing your input value and pulling the match of the second column.
To get your table you can take your source formula and replace (Find and Replace - Ctrl+H) some characters with unique delimiting characters. Then use Text To Columns Alt+D+E and delimit and Copy>Paste special>Transpose to quickly have it close to the format you need.

Find a value from a column and quickly return the row number of its cell

What I have
I have a file with part numbers and several suppliers for each part. There are 1500 parts with around 20 possible suppliers each. For the sake of simplicity let's say parts are listed in column A, with each supplier occupying a column after that. Values under the suppliers are entered manually but don't really matter.
In another sheet, I have a list of parts that is imported from an Access database. The parts list is imported, but not the supplier info. In both cases, each part appears only once.
What I want to do
I simply want to match the supplier info from the first sheet with the parts in the imported list. Right now, I have a function which goes through each part in the list with suppliers, copies the supplier information in an array, finds the part number in the imported part list (there is always a unique match) and copies the array next to it (with supplier info inside). It works. Unfortunately, the find function slows down considerably each time it is used. I know it is the culprit through various tests, and I can't understand why it slows down (starts at 200 loop iterations per second, slows down to 1 per second and Excel crashes) . I may have a leak of some sort? The file size remains 7mb throughout. Here it is:
Function LigneNum(numAHNS As String) As Integer
Dim oRange As Range, aCell As Range
Dim SearchString As String
Set oRange = f_TableMatrice.Range("A1:A1500")
SearchString = numAHNS
Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
'We have found the number by now:
LigneNum = aCell.Row
Exit Function
Else
MsgBox "Un numéro AHNS n'a pas été trouvé: " & SearchString
Debug.Print SearchString & " not found!"
LigneNum = 0
Exit Function
End If
End Function
The function simply returns the row number on which the value is found, or 0 if it doesn't find it which should never happen.
What I need help with
I'd like either to identify the cause of the slow down, or find a replacement for the Find method. I have used the Find before and it is the first time this happens to me. It was initially taken from Siddarth Rout's website: http://www.siddharthrout.com/2011/07/14/find-and-findnext-in-excel-vba/ What is strange is that it doesn't start slow, it just becomes sluggish as it goes on.
I think using Match could work, or maybe dumping the range to search (the part numbers) into an array and trying to match these with the imported parts number list could work. I am unsure how to do it, but my question is more about which one would be faster (as long as it remains under 15 seconds I don't really care, though, but looping over 1500 items 1500 times right out of the sheet is out of the question). Would anyone suggest match over the array solution / spending more hours fixing my code?
EDIT
Here is the loop it is being called from. I don't think it is problematic:
For Each cellToMatch In rngToMatch
Debug.Print cellToMatch.Row
'The cellsToMatch's values are the numbers I want, rngToMatch is the column where they are.
For i = 2 To nbSup + 1
infoSup(i - 2) = f_TableMatrice.Cells(cellToMatch.Row, i)
Next
'infoSup contains the required supplier data now
'I call the find function here to find the row where the number appears in the imported sheet
'To copy the array nbSup on that line
LigneAHNS = LigneNum(cellToMatch.Value) 'This is the Find function
If LigneAHNS = 0 Then Exit Sub
'This loop just empties the array in the right line.
For i = LBound(infoSup) To UBound(infoSup)
f_symix.Cells(LigneAHNS, debutsuppliers + i) = infoSup(i)
Next
Next
If I replace LigneAHNS = LigneNum by LigneAHNS = 20, for example, the code executes extremely fast. The leak therefore comes from the find function itself.
Another way to do it without using the find function might be something like this. Firstly, put the part IDs and their line numbers into a scripting dictionary. These are really quick to lookup from. Like this:
Dim Dict As New Scripting.Dictionary
Dim ColA As Variant
Lastrow=range("A50000").end(xlUp).Row
ColA = Range("A1:A" & LastRow).Value
For i = 1 To LastRow
Dict.Add ColA(i, 1), i
Next i
To further optimise, you could declare the Dict as a public variable, populate it once, and refer to it many times in your lookups. I expect this would be faster than running a cells.find over a range every time you do a lookup.
For syntax of looking up items in the dictionary, refer to Looping through a Scripting.Dictionary using index/item number
You could achieve this with only Excel cell formulas and no VB if you are willing to devote a separate column to each supplier on your main parts sheet. You could then use conditional formatting to make it more visually appealing. I've tried it with 1500 rows and it's very quick. Increasing it to 5000 rows becomes noticeably slower, but you say you have only 1500 rows for now, so it should be suitable.
On Sheet 1, define a part number column and a separate column for each supplier.
Create a separate sheet for each supplier with all part numbers available from that supplier listed in column A. Make sure the rows on the supplier sheets are ordered by part number.
Name each of the supplier sheets the same as the associated column heading shown on Sheet 1.
Assign the following formula in each cell beneath each supplier column heading on Sheet 1:
=NOT(ISNA(VLOOKUP($A2,INDIRECT("'"&B$1&"'!A:A"),1,FALSE)))
The following screen cap shows this implemented along with conditional formatting to highlight which suppliers have which parts:
If you wanted to show quantities available from suppliers, then you could always have a second column (B) on the supplier sheets containing last known quantities for each part and use VLOOKUP to retrieve column B instead of A.

Excel VBA Delete empty rows in table

I have a table tabelaClientes in Sheet "Clientes" and I want to delete the rows where the field "Nome" is empty.
How do I do that?
This is what I'm trying:
Sub Cliente()
Dim ws As Worksheet
Dim row As Range
Set ws = Sheets("Clientes")
For Each row In ws.[tabelaClientes[Nome]].Rows
If row.Value = "" Then
row.Delete
End If
Next
Exit Sub
But this is deleting only some of the rows where Nome is empty, not all, why?
You can use a very simple call to SpecialCells() to do that instead of using a loop.
Range("tabelaClientes[Nome]").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Edit: To expand on my answer because I was in a hurry. SpecialCells mimic the menu that you will find in Excel after having pressed F5 and selected "Special cells... Blanks". This has the advantage of selecting all blanks at the same time and then delete the rows. Iteration can be very slow if your table is getting large thus this way will save a lot of time.
It does seem that you cannot delete multiple non-contiguous rows in a table. You can do either one of two things:
1- Convert back the table to a range and change the reference to a standard excel reference
2- Loop through the results of SpecialCells().
Option #2 will yield in slower code because of the loop but it will still be better than looping through all cells and check if they are blank but I can understand that you may need to keep it as a table.