Vlookup using VBA - excel

I have a woorkbook with informations that I am adding into word.
Now I need to add a txt that I have to find by use of vlookup (or index match)
My code will not run, and after 6 hours I am near to give up, but hope, that one of you can help me.
The code is:
wrdApp.Selection.TypeText Text:=(Application.Function.VLookup(Cells((RowNo + i), ColumnForLevel2Text).Value, sectionT.Range("ab1:ac5"), 2, 0))
My Vba code is placed in anoter workbook. But that has not been a problem so far.
I want to lookup for the text in the cell (Range((RowNo + i), ColumnForLevel2Text)
I want to lookup in a range("ab1:ac5") at another sheet in the same workbook, called sectionT.
My text could be 1.1 and I would like to have the text "Result" typed into word.
Regards
Peter

I'm not sure I have everything to solve your problem, but I can help you split your problem into more manageable pieces. If you write your code like this:
Dim LookupValue, TableArray, OutputText
LookupValue = Cells((RowNo + i), ColumnForLevel2Text).Value
Set TableArray = sectionT.Range("ab1:ac5")
OutputText = Application.WorksheetFunction.VLookup(LookupValue, TableArray, 2, 0)
wrdApp.Selection.TypeText Text:=OutputText
you can follow it step by step and see where it went wrong. The big issue here is that you wrote Function instead of WorksheetFunction.

Related

MATCH and INDEX to return index number 2 Excel

I tried with the combination of CONCATENATE, INDEX and MATCH function, to get an overview table of which employees works which function a day.
Here is the setup:
And this should be the resulting table:
This is the formula I made:
=CONCATENATE(INDEX($B$5:$B$10,MATCH($B2,C$5:C$10,0)))
And obtain only the first index:
How can a return index 2 respectively: name3 and name5?
I have an Excel version prior to the 2016 version, and can't use the TEXTJOIN or CONCAT function.
EDIT
I tried to make the formula work even though the VBA solution works as well:
This is what I get to work:
=IF(COUNTIF(C$5:C$10,$B2)=0,"",IF(COUNTIF(C$5:C$10,$B2)=1;INDEX($B$5:$B$10,MATCH($B2,C$5:C$10;0)),INDEX($B$5:$B$10,MATCH($B2,C$5:C$10,0))&CHAR(10)&INDEX($B$5:$B$10,SMALL(MATCH($B2,C$5:C$10),ROWS(C$5)))))
It gives the correct solution in this case (assuming there are at most 2 matches), however it's fragile.
I tested it in a larger setup, where it returned the same name twice, and I can't figure out what the problem is.
Any idea, why that's the case?
Nothing pretty at all. But it does work.
User defined function.
Place this code in a module
Function name_find(func As String, namerng As Range, searchrng As Range)
For Each r In searchrng
If r.Value = func Then
name_find = name_find & Chr(10) & Cells(r.Row, namerng.Column).Value
End If
Next r
End Function
and use the formula:
=name_find(C4,C9:C14,D9:D14)
Remember to enable line breaks in the cell. It took me a while to understand why it didn't work :-)

Select Case with Complex Return Value (VBA 2007)

Using Excel 2007 and inexperienced with VBA.
I am trying to create a text generator where, given a particular type of entry, it returns a string of text AND a number of corresponding cells.
I have a lot of data to combine and somewhat complex text statements. The data I have here is sample data. The final file will combine multiple text strings ("one" and "two", etc) with multiple cells that need to be referenced based on the specific data input there (some instances require 8 different cells).
I was able to figure out how to do Select Case where it can look up the type of entry I need, and it returns a specific text string. Great! I also know I can combine things like "One" & "Two". But how do I combine the corresponding text for the line?
Where if the entry was "ID" I could return something that looked like "One 1" but combines "One " & K2 as the .Value to return?
Image shows the sample data
Image shows data for Columns I, J, and K.
Column I stores the entry type, J is where the data is returned, and K is the column with data to be referenced. Again, what's here is the simplified reference data.
I know this line is wrong. But I'm not sure what to put in place for K2 so it will correctly reference the cell, and then loop correctly for 300 times.
Case Is = "ID": .Value = "One" & (K2)
Am I close to something workable? What would you suggest? Is Select Case the wrong way to handle this problem?
I've tried a number of options, but I am inexperienced with VBA. I think whatever I implemented to fix the issue was likely done incorrectly.
Full code of what I have shown below.
Private Sub CommandButton1_Click()
Dim logtype As Range
For Each logtype In Range("I2:I302")
With logtype.Offset(0, 1)
Select Case logtype.Value
Case Is = "ID": .Value = "One" & K2
Case Is = "Phase": .Value = "Two"
Case Is = "Install New": .Value = "Three"
Case Is = "Install OH": .Value = "Four"
Case Is = "Install AR": .Value = "Five"
Case Is = "Insp": .Value = "Six"
Case Is = "LUI": .Value = "Seven"
Case Is = "": .Value = ""
Case Else: .Value = "Not Recognized"
End Select
End With
Next logtype
End Sub
EDIT:
What I put in a comment below, just formatted more clearly.
I want to create a macro that spits out the correct language of an entry based on the kind of work completed in a work order.
For example, ID or Install New and then return the correct language and reference data for the entry:
I2: ID
K2: Number (I'd type in the actual No.)
Returns:
"Complied with ID No. [K2]. No defects noted."
I4: Install New
L4: Actual part number
M4: etc...
N4: ...
O4: ...
Returns:
"Removed P/N [L4], S/N [M4]. Installed P/N [N4], S/N [O4]. Ops checked good."
Does that make sense? Thanks!
EDIT 2:
Hey everyone, I've tried tracking down alternative methods of solving this problem but I still haven't produced anything better than what I have here.
Any thoughts or help would be greatly appreciated. Thank you!
For each cell in Range("I2:I302")
cell.offset(0,1).value=cell.offset(0,1).text & cell.offset(0,2).text
next

Comparing Strings Producing Unexpected Results

I have a list of data and I created a form to enter new data to be added to the list. Upon the click of a button it will take the information (name and email address) from the form and add it to the corresponding sheets in alphabetical order. There are linked cells involved so I can't just add this to the bottom and sort. Instead, I have it searching the last name cell in the correct sheets to insert a row into the correct location.
This was working as expected for the most part until I came along a possibly unique situation that I can't figure out.
Basically, I have an if statement checking to see if the name is a duplicate and afterwards checking to see if the if the new name should be inserted.
For i = 2 To lastrow
''^^IF STATEMENT CHECKING FOR DUPLICATE^^''
'''''''''''''''''''''''''''''''''''''''''''
'''vvIF STATEMENT CHECKING TO ADD DATAvv'''
ElseIf StrComp(lastname, searchl) = 1 And StrComp(lastname, searchl2) = -1 Then
Sheets("Master List").Range("A" & i).Offset(1).EntireRow.Insert (xlDown)
Sheets("Master List").Range("A" & i + 1).Value = firstname
Sheets("Master List").Range("B" & i + 1).Value = lastname
Sheets("Master List").Range("C" & i + 1).Value = fullname
Variables searchl and searchl2 are the last names from search rows i and i + 1, respectively.
My problem is that when I tried to add the last name "Kralik" it tried to insert the data between the last names "Day" and "de Castro"
Originally, I tried comparing the names using the line of code below:
ElseIf lastname > searchl And lastname < searchl2 Then
This executed the exact same way as the code outlined above. I then inserted a break point and decided to use the StrComp method for troubleshooting. Comparing "Kralik" to "Day" produced results expected but the problem occurs when comparing "Kralik" to "de Castro". For some reason, the code thinks "Kralik" is less than "de Castro" and enters the if statement to insert the data at that location. Even more head scratching for me is that I opened a new workbook and quickly typed "Kralik" into A1, "de Castro" into A2 and the formula "=A1>A2" into A3. The formula gave a result TRUE which is what I would have expected from VBA as well.
EDIT: After more tests, I think it must have something to do with the capitalization of "Kralik" vs. "de Castro" my code works as expected as long as the "k" in "Kralik" is uncapitalized. I will use the UCase method on my variables and come back with the results.
EDIT 2: Using UCase works as well. Outlined by GSerg's answer below as to why my original method was not working.
Excel formulas use case insensitive comparisons by default.
VBA uses case sensitive comparisons by default.
If you want case insensitive comparisons, either put
Option Compare Text
at the beginning of the code module to make all text comparisons in that code module case insensitive by default, or request a comparison type in each specific comparison:
ElseIf StrComp(lastname, searchl, vbTextCompare) = 1 And StrComp(lastname, searchl2, vbTextCompare) = -1 Then
On top of that, you should be using binary search in your particular case to find the position to insert. MATCH with match_type = 1 will return you position in a sorted list where the value should go.

VBS Excel cell to SAP

I am struggeling to get the right informations from an Excel sheet via vbs script into SAP.
A single cell works fine and will be added into SAP but the original Excel sheet contains a cell where the last 4 digits needs to be deleted and afterwards combined with another cell and then added to SAP.
This works for me:
session.findById("wnd[0]/usr/tabsTABSPR1/tabpSP06/ssubTABFRA1:SAPLMGMM:2000/subSUB5:SAPLZMM_GINCOFIELDS:5802/ctxtMARC-PRCTR").text = (objSheet.Cells(6,"P") & (objSheet.Cells(38,"P")).Value)
But this dont:
session.findById("wnd[0]/usr/subSUBSCR_BEWERT:SAPLCTMS:5000/tabsTABSTRIP_CHAR/tabpTAB1/ssubTABSTRIP_CHAR_GR:SAPLCTMS:5100/tblSAPLCTMSCHARS_S/ctxtRCTMS-MWERT[1,1]").text = (objSheet.Cells(40,"F") & (Left((40,"F"), Len(40,"F") - 4)) & (objSheet.Cells(39,"L") & (objSheet.Cells(39,"O").Value)
The error message while starting the script means translated: ...at 207 ')' excpected...
Thanks in advance for having a look at this and providing help or a hint.
You are using Left(40,"F"): I suspect that what you actually mean is objSheet.Cells(40, "F"). Same with your Len call, I suspect what you actually want is: Len(objSheet.Cells(40, "F")). So putting that together:
Left(objSheet.Cells(40, "F"), Len(objSheet.Cells(40, "F")) - 4) & objSheet.Cells(39, "L") & objSheet.Cells(39, "O")

Add a space after colored text

I'm Using Microsoft Excel 2013.
I have a lot of data that I need to separate in Excel that is in a single cell. The "Text to Columns" feature works great except for one snag.
In a single cell, I have First Name, Last Name & Email address. The last name and email addresses do not have a space between them, but the color of the names are different than the email.
Example (all caps represent colored names RGB (1, 91, 167), lowercase is the email which is just standard black text):
JOHN DOEjohndoe#acmerockets.com
So I need to put a space after DOE so that it reads:
JOHN DOE johndoe#acmerockets.com
I have about 20k rows to go through so any tips would be appreciated. I just need to get a space or something in between that last name and email so I can use the "Text to Columns" feature and split those up.
Not a complete answer, but I would do it way:
Step 1 to get rid of the formatting:
Copy all text that you have to the notepad
Then copy-paste text from Notepad to excel as text
I think this should remove all the formatting issues
Step 2 is to use VBA to grab emails. I assume that you have all your emails as lowercase. Therefore something like this should do the trick (link link2):
([a-z0-9\-_+]*#([a-z0-9\-_+].)?[a-z0-9\-_+].[a-z0-9]{2,6})
Step 3 is to exclude emails that you extracted from Step2 from your main text. Something like this via simple Excel function:
=TRIM(SUBSTITUTE(FULLTEXT,EMAIL,""))
Since you removed all the formatting in Step1, you can apply it back when you done
You can knock this out pretty quickly taking advantage of a how Font returns the Color for a set of characters that do not have the same color: it returns Null! Knowing this, you can iterate through the characters 2 at a time and find the first spot where it throws Null. You now know that the color shift is there and can spit out the pieces using Mid.
Code makes use of this behavior and IsNull to iterate through a fixed Range. Define the Range however you want to get the cells. By default it spits them out in the neighboring two columns with Offset.
Sub FindChangeInColor()
Dim rng_cell As Range
Dim i As Integer
For Each rng_cell In Range("B2:B4")
For i = 1 To Len(rng_cell.Text) - 1
If IsNull(rng_cell.Characters(i, 2).Font.Color) Then
rng_cell.Offset(0, 1) = Mid(rng_cell, 1, i)
rng_cell.Offset(0, 2) = Mid(rng_cell, i + 1)
End If
Next
Next
End Sub
Picture of ranges and results
The nice thing about this approach is that the actual colors involved don't matter. You also don't have to manually search for a switch, although that would have been the next step.
Also your neighboring cells will be blank if no color change was found, so it's decently robust against bad inputs.
Edit adds ability to change original string if you want that instead:
Sub FindChangeInColorAndAddChar()
Dim rng_cell As Range
Dim i As Integer
For Each rng_cell In Range("B2:B4")
For i = 1 To Len(rng_cell.Text) - 1
If IsNull(rng_cell.Characters(i, 2).Font.Color) Then
rng_cell = Mid(rng_cell, 1, i) & "|" & Mid(rng_cell, i + 1)
End If
Next
Next
End Sub
Picture of results again use same input as above.

Resources