Write a VLOOKUP as a string in a cell with dynamic path retrieved through GetoOpenfilename - vba

I am trying to write a VLOOKUP in a cell as a string, with VBA. This means that I do not want the result to appear in the cell as a value, but I want the whole VLOOKUP expression instead (For this example : "VLOOKUP(C6,'[path_to_file.xlsm]OTD Table!$B:$F,4,0)"). The challenge is that the range argument of the VLOOKUP is a concatenation of a path (path_to_file.xlsm) that the user selects with a GetOpenFilename, and a string that specifies the tab in which the lookup table is located ("OTD Table!$B:$F,4,0").
The issue I am getting is very interesting :
When I print my expression in a Msgbox, the expression appears correctly. However, when I write it in a cell, the path mysteriously appears incorrectly.
Sub macro()
dim data_file_new as String
data_file_new = CStr(Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls*),*.xls*", Title:="Select new data file")) ' The user selects the file
str_ = "=VLOOKUP(C6," & "'[" & data_file_new & "]OTD Table!$B:$F,4,0)" ' This will display the expression correctly
cells(1,10)="=VLOOKUP(C6," & "'[" & data_file_new & "]OTD Table!$B:$F,4,0)"' This will not display the same thing as in the messagebox above
end Sub
I hope one of you guys can make sens of this !

Because you're dropping a formula into a cell that you want to display as straight text, you have to be explicit with Excel and tag the text string to prevent interpreting it as a formula. The simplest way to do this is pre-pend the string with a single-quote "'".
Sub macro()
Dim data_file_new, str_ As String
str_ = "'=VLOOKUP(C6,'["
data_file_new = CStr(Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls*),*.xls*", Title:="Select new data file")) ' The user selects the file
str_ = str_ & data_file_new & "]OTD Table!$B:$F,4,0)" ' This will display the expression correctly
ActiveSheet.Cells(1, 10).Value = str_
End Sub

Yeah either you'll need to set the string to add a single quote, or you'll need to change the numberformat of the cell to text (Cells(1,10).NumberFormat = "#")
Either of those should work.

Related

Turn String Into Hyperlink with Preset Name in Excel with VBA

I have a userform where I will be wanting people to enter a link e.g. bbc.com & I want the program to automatically turn this string into a hyperlink (blue underlined) called "website".
Here's what I have so far.
PublicProperty Get Link() as string
Link=Me.Linkbvalue
.cells(blankrow,1).value=me.link
EDIT: Note, words generic to protect company. Actually the problem is not it starting with local server. In the following the file is in the folder but not the subfolder
Entry="\directory\folders_directory\folder\file"
when running code,
address becomes
\directory/folders_directory\folder\sub_folder"\directory\folders_directory\folder\file"
The following might help.
It will convert column A values to hyperlinks.
Sub GetHyperlink()
For Each xCell In Range("A:A")
If xCell.Value <> "" Then
ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:="http://www." & Replace(xCell.Formula, "www.", ""), TextToDisplay:="Website"
End If
Next xCell
End Sub
This is something that should work, if you read the the entry variable from the Form:
Sub TestMe()
Dim entry As String
entry = "bbc.com"
Dim httpPrefix As String
httpPrefix = "https://"
If Left(entry, Len(httpPrefix)) <> httpPrefix Then
entry = httpPrefix & entry
End If
With Worksheets(1)
.Hyperlinks.Add Anchor:=.Cells(1, 1), _
Address:=entry, _
TextToDisplay:="website"
End With
End Sub
Some business logic is needed to decide whether to write https:// or http:// or anything similar. You may consider using Trim() to remove possible empty cells from the left and the right.

Adding values to a combobox based on another value VBA

I am currently trying to get a combobox to add items based on another combobox value, but am coming unstuck.
The following is the code I have so far - through trial and error I have got to this stage, although this is still giving me a "1004" error relating to the last line of the code. Is there a better way of writing this to get the same result?
Private Sub ProductInfo1_Change()
Dim strName As String
Dim strNameProductAllData As String
Dim strNameProductName As String
Dim strNameProductDescription As String
strName = Replace(OrderForm1.OrderFrm3.Value, " ", "")
sheet = "strName"
strNameProductName = Replace(strName, " ", "") & "productname"
strNameProductDescription = Replace(strName, " ", "") & "productdescription"
Me.ProductInfo2 = Application.WorksheetFunction.Index(Sheets(strName).Range(strNameProductDescription), Application.WorksheetFunction.Match(ProductInfo1.Value, Sheets(strName).Range(strNameProductName), 0))
End Sub
You are assigning to the wrong object.
You are trying to set a combobox, ProductInfo equal to a range.
What you want to do is use the "RowSource" property of the combobox
For example:
Me.ProductInfo2.RowSource = "mySheet!$A$1:$A$10"
This would make the choices for the ProductInfo2 combobox the items in cells A1-A10.
It is unclear what you are trying to get with the Match/Index Worksheet functions. If the contents of the cell have a range, then just use the contents to be equal to this rowsource. So for instance, if the column that represents "strNameProductDescription" has the range "myRange" in it, then your code can simply be modified to put this into the RowSource property. If it contains some other piece of information, then you need to construct the range you are looking for so that it would be similar to the line shown above. If myRange is a range on your worksheet, then the code,
Me.ProductInfo2.RowSource = "myRange"
will work.

Why is cell "A1" being used in this GetValue function in VBA?

I'm using this function to retrieve a value from a closed workbook. In this 8th line of this code, I don't understand why "A1" is being used. What exactly is happening in that entire 8th line? I'm confused by the xlR1C1 argument as well.
Private Function GetValue(path, file, sheet, ref)
Dim arg As String
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
GetValue = ExecuteExcel4Macro(arg)
End Function
Range().Range() Documentation here:
When applied to a Range object, the property is relative to the Range object. For example, if the selection is cell C3, then Selection.Range("B1") returns cell D3 because it’s relative to the Range object returned by the Selection property. On the other hand, the code ActiveSheet.Range("B1") always returns cell B1.
The code is using that second Range("A1") to ensure that if you have a ref range larger than one cell, it only returns the top left cell of that range. Also it would appear your other Sub called ExecuteExcel4Macro() requires an R1C1 type cell reference so the address is being converted into that type for passing the arg string into the Sub.
xlR1C1 is a reference style which is used to specify how formulas work. When using this style, your formulas will work and look very differently than you expect. The R1C1 specification, basically means the cells are referred to differently using row & column ordinals instead of letter names. For example, when using xlR1C1, you would access cell B2 by using =R2C2 (row2, column 2). Another Example, cell C10 could be referred to as =R10C3
As to whats happening on line 8... you are constructing a cell reference that looks like this: (Note that your cell reference will be different because it has a file path in it)
='[Myfilename.xlsx]Sheet1'!R1C1
You can use the debugger to view the string contained in the arg variable.
Adding Range("A1") to the code doesn't appear to do anything at all. Typing this into the immediate window results in some... unexpected results.
?Range("B3").Range("A1").Address
$B$3
Now, I would have expected that to return $A$1, but it seems that this part of the function will return the address of Range(ref).
Now, calling Range.Address with the ReferenceStyle argument would produce these results.
?Range("B3").Range("A1").Address(,,xlR1C1)
R3C2

VBA - Excel create a hyperlink using the sheets command and cells method

Q1: The routine below does not work.
Sub test()
TXT = Sheets("INDEX").Cells(2, 1).Value
AKO = Sheets("TOBESEEN").Cells(1, 1).Address
Sheets("INDEX").Hyperlinks.Add Anchor:=Sheets("INDEX").Cells(1, 2), Address:="",
SubAddress:=AKO, TextToDisplay:=TXT
End Sub
Q2. Is there a place where I can see ALL the properties of the cell? When I type the "dot" after cells, VBA DOES NOT GIVE any options.
Like
sheet1.cell(1,2).VALUE
sheet1.cell(1,2).ADDRESS
sheet1.cell(1,2).?
I suspect my problem is related to the definition of AKO, but I am not sure what the correct property is (if not ADDRESS)
Thank you
Q1: Try to use this code:
Sub test()
TXT = CStr(Sheets("INDEX").Cells(2, 1).Value)
AKO = Sheets("TOBESEEN").Cells(1, 1).Address
Sheets("INDEX").Hyperlinks.Add _
Anchor:=Sheets("INDEX").Cells(1, 2), _
Address:="", _
SubAddress:=Sheets("TOBESEEN").Name & "!" & AKO, _
TextToDisplay:=TXT
End Sub
Q2: you can use F2 help. There you can see a list of properties and methods of any object.
When you create a hyperlink in a document, you need to give the "full" address of the cell you are linking to (sheet name and cell address), not just the .Address (which is the absolute address on a given sheet, but doesn't include the sheet information). To get the full address (including the sheet) of a cell, you need to add an additional parameter to the Address():
.Address(External:=True)
which will give you the full address, including workbook and sheet name. Unfortunately, if you create this link and then change the name of the workbook (maybe because you had not saved it up to this point), the link will break.
It is therefore (slightly) more robust to create a link that doesn't include the workbook name. The following routine does this for you. Note that is usually a good idea to split your code into small self-contained functions that do one thing particularly well - you can re-use your code more easily, and the main program becomes easier to read and maintain. I suggest therefore that you create the following function:
Sub addLink(target As Range, location As Range, text As String)
' create a hyperlink with text "text"
' in the cell "location"
' pointing to the range "target"
Dim linkAddress As String
linkAddress = target.Address(external:=True) ' this is the "full" address
'remove everything between brackets - this is the workbook name:
bLeft = InStr(1, linkAddress, "[") ' location of left bracket
bRight = InStr(bLeft, linkAddress, "]") ' location of right bracket
linkAddress = Left(linkAddress, bLeft - 1) + Mid(linkAddress, bRight + 1)
' now create the link:
location.Parent.Hyperlinks.Add _
anchor:=location, _
Address:="", _
SubAddress:=linkAddress, _
TextToDisplay:=text
End Sub
You can call this from your code above as follows:
Dim TXT As String, AKO As Range, LOC As Range ' define types when possible
TXT = Sheets("INDEX").Cells(2, 1).Value ' I called this text
Set AKO = Sheets("TOBESEEN").Cells(1, 1) ' I called this target (note - need Set)
Set LOC = Sheets("INDEX").Cells(1, 2) ' I called this location
addLink AKO, LOC, TXT
As for the second part of your question - "I can't see the properties of Cells()". Yes, that is annoying. It happens that Cells() is a lot like a Range object; you can see in the above that I was able to do Set AKO = Sheets("TOBESEEN").Cells(1,1) which demonstrates this. You can declare a variable as being of the type Range, and then tooltips will work for you:
Dim r As Range
r.
and as you type r. you will see a list of the properties of Range (which are also the properties of Cells):
It is annoying that Cells doesn't just do this by itself. It is annoying that Address() doesn't have an option to include the sheet name and not the workbook name. Excel is full of annoyances. In fact, there is even a book called "Excel Annoyances". And more could be written, I'm sure…
At least there are usually VBA tricks to work around these things and get the job done.

VBA - Get Cell Values from other workbook without opening

I'm working to get the cell value of other workbook without opening it.
And here's some of my codes:
Range("F3")= "='C:\inetpub\vhosts\hotdogko.com\httpdocs\private\excel\[Launch Pad.xls]Sheet1'!$B$12 "
This code is working well when data type of the cell value to pull is Date, Integer or Any not String data type. But it wont work correctly to string data type, it just returning #N/A.
Thanks for someone who can give me an answer for this problem.
You can try with following answer
Sub ReadDataFromAnotherWorkBook()
' Open Workbook A with specific location
Dim src As Workbook
Set src = Workbooks.Open("C:\Users\chan.yoonghon\Desktop\Excel\BookA.xlsx", True, True)
Dim valueBookA As Integer
Dim valueBookB As Integer
valueBookA = src.Worksheets("sheet1").Cells(1, 1)
Cells(1, 1).Value = valueBookA
' Close Workbooks A
src.Close False
Set src = Nothing
' Dialog Answer
MsgBox valueBookA
End Sub
If you add the text function after the equal It should work something like:
Range("F3")= "=text("'C:\inetpub\vhosts\hotdogko.com\httpdocs\private\excel\[Launch Pad.xls]Sheet1'!$B$12 " ;"") "
Perhaps you should check if the " are correct because sometimes you have to add double "".
Try it without using quotation marks (" "). It should help.