There have been a few posts about this, but cannot find anything relating specifically to my problem.
I want to have a WHERE search on a named range within VBA where the range is changeable e.g not simply A1:A10, but A1:End
I have tried the below, but only the last cell within the range is used in the SQL WHERE results
Set Brokers = Sheets("Brokers").Range("A2").End(xlDown)
Dim r As Variant
r = Brokers.Value
....
WHERE c_broker = '" & r & "'"
I have also tried the below, but am getting a "type mismatch" error
WHERE c_broker IN( '" & Join(Application.Transpose(Sheets("Brokers").Range("A2").End(xlDown).Value), "','") & "')"
If anyone could help - or let me know if not possible at all - that would be great!
Thanks!
EDIT:
To further explain this, I have a range in sheet "Brokers" starting from A2 going down where the end can change depending on user input e.g it can be A2:A10 or A2:A15. I want SQL to pick up on this range at whatever it currently is, which is why I've been trying to use End(xlDown) in the VBA. I have tried changing the above to the below, but am having an "Application-defined or object-defined error"....the same goes when I add this in the SQL WHERE line - unless I am doing something incorrect with the below?
Set Brokers = Sheets("Brokers").Range("A2", Range("A2").End(xlDown))
Related
Having some trouble with my macro where I need to inject two ranges into a SQL query. The reason being that it exceeds Excel's character limit for 1 cell, so I have used a formula to split the query between 2 (keeping in mind spaces for the split to keep the syntax correct).
However, my VB to inject both the ranges together is not working so it's clear there's something I'm not considering correctly. The error is Run-time error 1004: Application-defined or object-defined error
Here's how it currently appears:
With ActiveWorkbook.Connections("Qry").ODBCConnection
.CommandText = Range("Cell1") & Range ("Cell2")
End With
I have also tried to add .Value, as well as declaring the ranges before and then calling them. Note: Cell1 is the name I have given the cell.
When using Debug.Print on Range("Cell1") & Range ("Cell2"), the statement is jumbled, Cell1 starts midway before joining correctly into Cell2, then the beginning part of Cell1 abruptly starts again.
Immediate window is limited to 200 lines so debug.print won't show the full text. Write the sql to a file and maybe test it in database client.
Dim sql as string, ts
sql = Range("Cell1") & Range("Cell2")
With CreateObject("Scripting.FileSystemObject")
Set ts = .createTextFile("debug.sql")
ts.Write sql
ts.Close
End With
I am working in Excel vba and want to read the result of a VLookup formula.
When I insert the formula itself into a cell...
Range(Cells(1, 1), Cells(1, 1)).FormulaR1C1 = "=VLookup(" & ent & ", " & MyName & ", " & fc & ", FALSE)"
...everything works. But when I try to read the same formula and keep the result into a variable...
MyResult=Application.WorksheetFunction.VLookup(ent, MyName , fc, False)
..., id does not work and reports an Error no. 1004.
Any ideas? Just for clarification, these are the arguments of the formula: the range is defined with a name in another workbook. This is not a problem when inserting the formula in "A1" cell.
et = 4529
ep = 1
fc = 3
ent = 9992
MyRoute = "C:\WORK\MyEstates\"
MyBook = MyRoute + CStr(et) + "\" + CStr(et) + "-data.xlsx"
MyName = "'" + MyBook + "'!D_" + CStr(ep)
Application.WorksheetFunction.VLookup needs a range as the second parameter. It doesn't know which worksheet or cells to look in.
This is what you're calling it with:
Application.WorksheetFunction.VLookup(9992, "'C:\WORK\MyEstates\4529\4529-data.xlsx'!D_1", 3, false)
Try something more like:
Application.WorksheetFunction.VLookup (9992, worksheets("Sheet1").range("A1:b10"),3,FALSE)
If you need to use a variable then make sure you declare it as a Range.
(By the way, that was the first hit on a Google search.),
EDIT:
I realized afterwards what you're trying to do! :)
You shared lots of information but it was so convoluted I couldn't understand what the issue was, and the strange syntax (like Range(Cells(1, 1), Cells(1, 1))) and open-ended description (like Everything works) made it more confusing.
Before you get the answer, I might as well rewrite the question for you, so you get a better idea how to make it easier on everyone next time. Rewriting your question took me half the time it did to understand it, plus you would have answered your question yourself if you had just Googled the Error.
Error 1004 on WorksheetFunction.VLookup to external named range
Hi!
I have a VLookup formula which returns the expected result from a
named range in another workbook when I assign it to a cell using
this VBA:
Range("A1").FormulaR1C1 = _
"=VLookup(9992, '*C:\myPath\fileName.xlsx'!namedRange*, 3, FALSE)"
I can't get the same VLookup formula to work with
Application.WorksheetFunction like this:
myResult = Application.WorksheetFunction.VLookup _
(9992, "'C:\myPath\fileName.xlsx'!namedRange, 3, FALSE)"
VBA stops on the line above with this
error:
Run-time error '1004':
Unable to get the VLookup propery of the WorksheetFunction class
Next, I looked up the error and the very first Google search result
was an existing answer from Stack Overflow with the solution to my
problem.
So, I.......
.
I guess that's as far as I can go with the example question since the process of adding a couple links would have answered the question.
Here's your fix:
myResult = Application.WorksheetFunction.VLookup _
(9992, "'C:\WORK\MyEstates\4529\4529-data.xlsx'!D_1", 3, false)
Please read over How to create a Minimal, Complete, and Verifiable example and How to Ask. Thanks for your time!
I am trying to enter a Vlookup formula into Column S of a worksheet named "FY_16". I need the user to select the file (which changes each month) that the "table array" for the formula is in.
Each month the file changes, but the column I want to look up to will always be the same - Column W (but have varying number of rows). The "table array" that the formula will look up to is part of a table.
My code at this point is below:
Private Function UseFileDialogOpen()
MsgBox ("When the browse window opens: please select the previous months published FY16 Consulting SKU File")
Dim myString As String
' Open the file dialog
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count = 1 Then
myString = .SelectedItems(1)
'MsgBox myString
UseFileDialogOpen = myString
Else
MsgBox ("Failed to properly open file")
myString = "fail"
UseFileDialogOpen = myString
End If
End With
End Function
Sub Vlookup
Dim filelocation 'as what?????
filelocation = UseFileDialogOpen()
Worksheets("FY_16").Range("T2:T" & LastRow).FormulaR1C1 = "=vlookup(RC[-3], [" & myString & "] PA Rev!R1C23:R900000C23,1,false)"
My issue occurs on the final line of code. I receive a "run time error 1004 : application defined or object defined" message.
I know my syntax is incorrect for the vlookup in a few ways. I am not sure the "& myString & " is correct, perhaps this should be "filelocation"?
I also don't believe R1C1 can be used to name a range like I have in the vlookup. I typically would use
.Range(Cells(2,23), Cells(90000,23))
But I am not sure how to use that with the variable that holds the selected file name.
Also, I am using the 90000 row because this will go past my data each month (usually row count is around 75000). I would much rather find the exact row number but I don't believe this can be done without opening the "target file" selected by the user. If there is a way to achieve this, please offer any advice!
I am wondering if there is a way to use the Table Names to set the table array?
The non-VBA vlookup is as follows:
=VLOOKUP(Q2,'TargetFile.xlsb'!REV[[#All],[Net New Match]],1,FALSE)
TargetFile is the user selected file
REV is the worksheet the table array is on
Net New Match is the column I want to look up to (the entire column)
I played around with using these table names but couldn't get the syntax correct (possibly because the rest of the formula code is incorrect also).
Any help will be greatly appreciated. Let me know if any clarification is needed.
Mike
The correct syntax for accessing a range in an unopened workbook would be something that looks like 'C:\Temp\[Book2.xlsx]PA Rev'!R1C23:R900000C23. That won't be the same format that comes from the UseFileDialogOpen function.
You also can't use myString within your Vlookup subroutine because you defined that variable to be local to UseFileDialogOpen - but you can use filelocation which you have used to store the result from UseFileDialogOpen. But, as I said, it won't be in the right format anyway, so it will require a bit of reformatting.
The following command should do the necessary reformatting:
Worksheets("FY_16").Range("T2:T" & LastRow).FormulaR1C1 = _
"=vlookup(RC[-3],'" & Left(fileLocation, InStrRev(fileLocation, "\")) & _
"[" & Mid(fileLocation, InStrRev(fileLocation, "\") + 1) & _
"]PA Rev'!R1C23:R90000C23,1,false)"
I'm getting a syntax error when I try to insert a formula in a cell using Macro. I can't seem to figure out what am I doing wrong? The formula works fine when I manually enter it. Here's my code:
ws3.Range("F2:F" & lastRow3).Formula = "=INDEX($L$1:INDEX(L:L,MATCH("ZZZ",D:D)),AGGREGATE(15,6,ROW($K$1:INDEX(K:K,MATCH("ZZZ",D:D)))/($K$1:INDEX(K:K,MATCH("ZZZ",D:D))=D2),COUNTIF($D$1:$D2,D2)))"
ws3 is the worksheet, and lastRow3 is just to autofill the contents by comparing to a column to the left. Any ideas why this is giving an error?
FYI: This formula is finding values in one column from another column and giving the adjacent entries.
When filling a full range it is best to use R1C1 format.
Also with using vba to set the last row there is no reason for all the INDEX(L:L,MATCH("ZZZ",D:D)) to find the last row, since the code itself can set it directly.
Use this:
ws3.Range("F2:F" & lastRow3).FormulaR1C1 = _
"=INDEX(R1C12:R" & lastrow & "C12,AGGREGATE(15,6,ROW(R1C11:R" & lastrow & "C11)/(R1C11:R" & lastrow & "C11=RC[-2]),COUNTIF(R1C4:RC4,RC[-2])))"
Warning: I'm a noob.
I've written a Sub to find cells with red text and alter them.
#ThinkerIV gave me a great function to put in a cell and drag the formula out into adjoining cells, but that won't work due to the number of sheets to work on.
So I wrote my Sub, calling his function (see code below). I passed it a Range of one cell, so it seems to me it should work?
But, it keeps throwing out Type Mismatch (run-time error code 13) on the line where the function calls the DateValue()! The passed range shows a value of 1 (which is the number in the cell it refers to) when I hover over it in the editor, but I don'rt know if that's the cell's contents or some other value 1 being shown.
So, I really don't know how to find out exactly why this is happening. Is it that the range I passed is somehow not the right kind? Please inform me of why this code won't work!
I tried to change that line to the comment line below it (and a couple other blind-guess changes), but that has the same error.
Thanks in advance!
Sub redTextToRealDates()
Dim dateTemp As Date
Dim redCell As Range
Dim foundCell As Range
Dim thisSheetsRange As Range
Dim busyCell As Range
Dim redTextCells As Range
Set thisSheetsRange = ActiveSheet.usedRange
'Build a range containing all the cells in a sheet containing red text.
' well... all cells formatted to HAVE red text, anyway.
' Anyone want to tell me how to write this to skip empty cells?
' Because I don't need to grab empty cells into this range...
For Each busyCell In thisSheetsRange
If (busyCell.Font.ColorIndex()) = 3 Then
If redTextCells Is Nothing Then
Set redTextCells = busyCell
Else: Set redTextCells = Union(redTextCells, busyCell)
End If
End If
Next busyCell
'Change unknown format cells to date cells populated with concantenated
'string of original contents and the active sheet's name.
For Each foundCell In redTextCells
foundCell.NumberFormat = "#"
foundCell = GetConcantDate(foundCell)
Next foundCell
redTextCells.NumberFormat = "dd/mm/yy"
On Error Resume Next
End Sub
Function GetConcantDate(rng As Range) As Date
'Original code supplied by ThinkerIV on StackOverflow.com
Dim dtTemp As Date
dtTemp = DateValue(rng.Range("A1").Value & " " & rng.Parent.Name)
'dateTemp = DateValue(foundCell.Value & " " & ActiveSheet.Name)
GetConcantDate = dtTemp
End Function
EDIT
I cant post my own answer yet, so I am adding this solution:
When feeding data to Format(), the contents of the first cell formatted for red were NOT in text form. I had not put in place any way to ensure that I passed the proper data type. So, the line to format the cell as text (foundCell.NumberFormat = "#") before passing it to the function is what fixed it.
The solution was actually already written when I copy/pasted the code into the question - I just wasn't aware that it had fixed it because of another error on a different Sub. (I'm a noob and was confused dealing with multiple errors in multiple subs) I thought I had tried it again with that new line, but HADN'T, so still thought it was not working.
Thanks to all who helped. I feel a bit of a fool now, having found it like that. Hope you forgive me for my rookie flubber - too many Subs and Functions in a huge list in the editor and I got 'dizzy'... At least I can post a solution in case some other noob needs it!
Ok, I think there are two things here. Firstly, the DateValue function takes a string representation of a date, e.g. "01/01/2013", when you pass through an excel date from a range, you are passing through a number, like 41275. This throws the run time error 13.
However, if you already have a date, why bother converting it? You seem to want all red cells to be converted to a date + the sheetname. To do this you'll have to have strings e.g. "01/01/2013 Sheet1", so you couldn't use DateValue here. Instead perhaps try something like this:
Public Function GetConcatDate(rng As Range) As String
Dim dtTemp As String
dtTemp = Format(rng.Range("A1").Value, "dd/mm/yyyy") & " " & rng.Parent.Name
GetConcatDate = dtTemp
End Function