Creating a Macro in Excel 2007 to extract moving data - vba

I have one sheet which is comprised of data that was imported from a web page. In a second sheet I have a cell asking for min price and max price which comes from the imported data. The issue is that the data can move to different cells when it's refreshed so my code needs to look for some specific wording to find the prices that I need rather than just directing it to the same cell each time
The info in the imported data sheet which I need to extract from will always be in this string of text which will always be found somewhere between row 15-35 but will move when the website is refreshed. The 1st number (71.00) needs to be extracted to another sheet in a cell asking for min price while the second number (75.00) is the max price. These prices can change so I can just look for those numbers and extract them.
SLAUGHTER BULLS: Yield grade 1-2 1000-1500 lbs
1500-2000 lbs 71.00-75.00.
Could someone please help me with the coding for this macro?

Use the InStrRev function (similar to the LastIndexOf function in .NET) to find the last index of "lbs" in the test string.
lastIndex = InStrRev(testString, "lbs", 1, 1)
Then search from that last index to the end of the string spliting on the -
splitArray = Split(Mid(testString, lastIndex, Len(testString) - lastIndex), "-", 1)
The lowest value will be in splitArray(0) and the upper value will be in splitArray(1) assuming a zero indexed array.

Related

Search xlsx for a value, if found replace with different value

So I'm either being too specific, or not searching well enough, because I can't find anything that answers my question. So I came here for help. Here is the situation:
I have an excel sheet, let's call it "CustomerCodeReference", that has a column (A) of Customer Codes (I.E. A2001, A2002, B3900, Q2838, etc, these are NOT necessarily in order) About 3000 of them, and in the next column over (B), I have the group that code represents (I.E. Accounts Primary, Accounts Secondary, Admin Group, User Group, just different names and etc.)
Now, from our company server I can export a spreadsheet of reports from customers, but the problem is, they are labelled by customer code, + a report serial number. The sheet exports as several columns, but one of the columns (G) contains the Customer code and serial number, and each row is a report, sometimes hundreds depending on the date range set. So keeping with the example, let's say it's a report from "Accounts Primary" It's labelled A2001234567 (where everything after the customer code of 'A2001' is the report serial number) sometimes, the report may be from several customers, so that column may have more than one code+SN in it per row.
Given that I have thousands of these codes and groups, is there some macro I can create that every time I export the spreadsheet of reports, I can maybe copy over the "CustomerCodeReference" sheet, and have it automatically search the column of customer codes and SNs, then either replace the code with the actual name, or place the actual name in another (empty) row further back. So I can basically easily reference whose report it is without having to look up the code each time?
I realize I will need to do this in VBA, as there is no formula I can think of that will work.
I have some pro's I think going for me:
-I already have the Master code list, so even though there are thousands of codes, they are all listed in Column A, and the actual name of group they reference is in column B.
-The codes are consistent, a letter, followed by 4 numbers, so always 5 characters long.
-When pulling the report, it always names the worksheet "Customer Reports" so it's easy to reference
These are constants. So I need the actual customer name to either replace the code (while leaving the serial number intact) or if easier, add the actual name to the next empty column on the same row. I also might need to share this with coworkers, so basically just send them the "CustomerCodeReference" sheet and when they add it to all their pulled spreadsheets, it does the same thing. (Macros will be enabled, so no worries there)
Is this too complicated an idea? or can I pull it off? Thanks in advance for the help!
EDIT: I apologize, I complete forgot to attach any sort of code. Here is what I have come up with in VBA, but not sure if I am on the right track as it does not complete the replacement, and I can't quite get it to add values in next available empty cell.
Sub replaceStringInCell()
'declaring my sheet I want to change change customer codes in
Dim CustomerCodes As Range
'declaring strings I will be replacing and with what I will be replacing them
Dim ReportNumbers As Range
Dim CustomerNames As Range
'identifying column I am working to replace, also trying to shoot for next empty column
Set CustomerCodes = PulledReports.Worksheets("Customer Reports").Range("G:G")
'specifying my strings
ReportNumbers = PulledReports.Worksheets("Customer Reports").Range("G:G")
myReplacementString = PulledReports.Worksheets("Customer Code Reference").Range("A:A")
'replace string in cell
CustomerCodes.Value = Replace(Expression:=CustomerCodes.Value, Find:=ReportNumbers, Replace:=CustomerNames)
End Sub
This should do the trick:
Sub stack_overflow()
Dim cust As Worksheet
Dim ref As Worksheet
Set cust = ActiveWorkbook.Worksheets("Customer Reports")
Set ref = ActiveWorkbook.Worksheets("Customer Code Reference")
'Finding next empty column
Dim column As Integer
column = cust.UsedRange.Columns.column + 1
'Filling this columns
For Each cell In cust.Range("G2:G" & cust.Cells(Rows.Count, "G").End(xlUp).Row)
cust.Cells(cell.Row, column).Value = Application.WorksheetFunction.VLookup(Left(cell.Value, 5), _
ref.Range("A2:B" & ref.Cells(Rows.Count, "B").End(xlUp).Row), 2, False)
Next cell
End Sub

Get the id of the selected value in a dropdown validation list on Excel in VBA

Using Excel, lets say I have a validation list made of 5 values like this one :
Patate
Tomate
Courgette
Concombre
Patate
In a cell containing a drop down list made of these 5 value, I select the fifth value : "Patate".
I want to get in VBA that this cell contains the 5th value of my validation list. Something like :
x = Cell.Validation.GetIDValueSelected
x = 5
I can't use Vertical search because I might have 2 or even more time the same value in my list (too long to explain why).
This list is also dynamics (depending of another sheets) so it doesn't always contains 5 values.
I hope I made it clear for everyone to understand my needs but I will be glad to add more information if needed.
Thank you for your time.
Sadly, once you have used DV to fill a cell with junk, there is no way to tell which piece of junk you picked:
You would have to pad each piece of junk with a different number of blanks.

VBA/EXCEL Dynamic Named Range That Includes Both Text and Numbers

Information
I have a column of about 300 part numbers that is constantly expanding. These part numbers can be only numbers, only letters, or a combination of both. I'm using dynamic named ranges with the part numbers to fill combobox lists. When the user types in the part number in the combobox, if we've done that part before it will autofill as they keep typing. I've recently ran into a problem with this however with a recent group of parts that was added.The part number is just a six digit number, and are the only part part numbers that solely consist of numbers, every other one has letters, or if its just numbers there are hyphens in the part number. The combobox I'm filling with this named range does show these numerical part numbers in its list, but does not autofill them when the user types and does not autofill the other information associated with the part number in other textboxes when the part number is done being typed in.
Question
Can anyone help me understand why it isn't autofilling the numerical value but it fills every other value?
Code
Here is the code I'm using to fill the combobox list and the dynamic range formula. Let me know if you need anything else to help you give an answer.
=OFFSET('Part List'!$A$1,0,0,COUNTA('Part List'!$A:$A),1)
comboxPartNumber.List = Range("Part_Number").Value
List of Sample Parts
X-600-ASSY-SM
LO-5093-020-023
LO-5093-020-025
AB-1541754
764761
766415
I cannot add a comment, sice I am 2 points short :(, so I am forced to post this as a solution:
Try to make all the numbers strings.
Dim R As Range
For Each R In Range("Part_Number").Cells
If IsNumeric(R.FormulaLocal) Then R.FormulaLocal = "'" & R.FormulaLocal
Next
Let me know if it worked.

Copy cells if specific text is found

I seem to have a problem and currently have not found a solution to it, which is why I address this question to you:
Each day I have a list of invoices and orders coming from different suppliers, and the orders are based on part numbers and types.
This list is imported as text and then goes through a macro I made, to arrange everything in cells.
I also need to go through some steps to format this list based on the type of order (ex: windshield, carpets, wheels, etc ). what I usually do is to filter everything and select the order type that I am interested, and then copy on the same row cells with text and formulas from another worksheet, named "template", which is a list of conditions .
Since it varies from day to day, it may not necessarily contain all part types, which is I couldn't use a macro, and I have to continue by hand, and sometimes the list exceeds 200-300 lines.
To give you an example, if E2 has "windshield" I copy in M2 to Q2 a selection of cells from "Template" (M2 to Q2), if "carpets" I copy M3 to Q3, and so on. the list of conditions is around 15 - 20 rows, and sometimes 2 conditions may apply (if order exceeds $5000 I mark it red, if overdue I bold everything, etc) but mainly I copy based on text in coll E.
If this could be copied into a macro, I would really appreciate it, as I need to take some steps every time, like auto-fit, copy header, format the amounts as number (from text), change text color based on order type, etc, and this too takes time.
I hope this information is enough to make an idea about this, and if not, I could post an example of the list I have to work with.
Many thanks in advance for your support
Use Application.Worksheetfunction.Match to find in which row in Template the to-be-copied cells can be found, then copy range M-Q for this row and paste in your file
You are asking too much in one question to get help here. We are best at single issue questions. The text and code below is intended you give you some ideas. If your code does not work, post the relevant part here and explain the difference between what it does and what you want it to do.
The problems you mention do not sound difficult. I would expect basic VBA to be enough to get you started. Are you looking for bits of relevant code without learning VBA. If you are, this is a big mistake. Search the web for "Excel VBA tutorial" or visit a large library and review their Excel VBA Primers. There are many tutorials and books to choose from so select one that is right for you. The time spent learning the basics will quickly repay itself.
Dim RowCrnt As Long
Dim RowLast As Long
With Worksheets("xxxx")
RowLast = .Cells(Rows.Count,"E").End(xlUp).Row
For RowCrnt = 2 to RowLast
' Code to process each row goes here
Next
End With
The above is probably the structure of your code. The For loop will examine each row in turn which will allow you to take relevant actions.
I have used "E" as a column letter because your question suggests column "E" is the most important. However, code that references columns in this way can be very confusing. Worse, if the column positions change, you will have to work carefully through your code changing the column letters. Better to have some statements at the top like this:
Const ColDate As String = "A"
Const ColAmtInv As string = "B"
Const ColAmtPaid As string = "C"
Const ColProdType As String = "E"
With these constants every reference to a column uses a name not a letter. The code is easier to read and, if a column moves, one change to the constant statement will fix the problem.
The Select Case statement is useful:
Select Case .Cells(RowCrnt, ColProdType).Value
Case "carpets"
' code for carpets
Case "windshield"
' code for carpets
Case Else
' Unknown product type
.Cells(RowCrnt, ColProdType).Font.Color = RGB(255, 0, 0)
End Select
You can have a string of If statements so multiple actions can occur on a single row:
If DateAdd("m", 1, .Cells(RowCrnt,ColDate).Value) < Now() And _
.Cells(RowCrnt,ColAmtInv).Value) > .Cells(RowCrnt,ColAmtPaid).Value Then
' Invoice overdue
.Rows(RowCrnt).Font.Bold = True
End If
If .Cells(RowCrnt,ColAmtInv).Value) > 5000 Then
' Large invoice
.Rows(RowCrnt).Font.Color = RGB(255, 0, 0)
End If
You do not have to write the entire macro in one go. If most action is because of the product type then try that first.
Hope this helps get you started.

VBA: Copy number from a string of text and insert into cells below

I want to create a makro in Excel which performs - after pressing a button - the below. I attached some dummy data that is formatted like the actual sheet.
There are several data blocks that are seperated by headlines in Sheet 1. From these headlines, I want to get a string of numbers and put it into column S for each line with data below that heading. In line 6 the heading says "2000", thus lines 8-19 should have a "2000" in column S and so on. The number I want to get is always after the word "Monthlyaccount" but the lenght of the number can be different - from 1 to 7 digits.
For lines where no data is given (data lines might be recognized by looking if in A is a valid date given) there should just be "ERR" instead of the number.
Can anyone help out?
Thanks so much upfront!
Say the string (in cell A1) contains "Monthlyaccount" followed by a blank followed by a number followed by another blank. To extract the number, use:
=--LEFT(MID(A1,FIND("Monthlyaccount",A1)+15,9999),-1+FIND(" ",MID(A1,FIND("Monthlyaccount",A1)+15,9999)))
This does as requested. Paste the following into S3 and drag down
=IF(AND(ISNUMBER(RIGHT(A2,4)*1),ISNUMBER(RIGHT(A3,4)*1)),S2,IF(ISNUMBER(RIGHT(A3,4)*1),LEFT(RIGHT(A1,LEN(A1)-FIND("Monthlyaccount",A1)-14),FIND(" ",RIGHT(A1,LEN(A1)-FIND("Monthlyaccount",A1)-14))),"ERR"))