VBA Type Mismatch when returning string to a value - vba

Fairly new to VBA but I have the following function that runs up until the Workbooks(PDwb).Sheets("pivotdata").Range("E2").Value = "ON-HAND" then returns a Tpye Mismatch Error.
The full code checks a cell from a different workbook so I don't know if that is causing the error.
Function IfCheck(Cell As Variant)
If Cell = "ON_HAND" Or Cell = "ON HAND" Then
Set PDwb = ActiveWorkbook
Workbooks(PDwb).Sheets("pivotdata").Range("E2").Value = "ON-HAND"
Else
Set PDwb = ActiveWorkbook
Workbooks(PDwb).Sheets("pivotdata").Range("E2").Value = Cell
End If
Set BOwb = ActiveWorkbook
End Function
I can't for the life of me work out what to do differently :S
Many Thanks,

The Workbooks(PDwb) function expects a string as parameter. But PDwb already IS the workbook.
Try
PDwb.Sheets("pivotdata").Range("E2").Value = "ON-HAND"

Related

Implement Vlookup formula on VBA, and handle error 1004

I start my adventure with VBA. I would like to create formula on VBA, use vlookup but something is going wrong with this.
Also I would like to implement vlookup for cells, when
cells from deferent column will be filled
( for example if WB_WS_Pricing.Range("A4")<>0 then
WB_WS_PRICING.Range("CX4") = "=IFNA(VLOOKUP(Delivering!E4,DATA!A:I,9,0),"")"
Sub formula()
Set WB_CMSO_MASS_IBERIA = ThisWorkbook
Set WB = ThisWorkbook
Set WB_WS_PRICING = WB.Sheets("Pricing")
Set WB_WS_HEADER = WB.Sheets("Header")
Set WB_WS_DATA = WB.Sheets("DATA")
Set WB_WS_Extension = WB.Sheets("Extension")
Set WB_WS_DELIVERING = WB.Sheets("Delivering")
WB_WS_PRICING.Range("CX4") = "=IFNA(VLOOKUP(Delivering!E4,DATA!A:I,9,0),"")"
End Sub
Enyone has idea what is wrong?? For me the formula seems be fine...
You need to escape the double quotes in your formula with an extra quote in front of each (ie """" not "")
WB_WS_PRICING.Range("CX4") = "=IFNA(VLOOKUP(Delivering!E4,DATA!A:I,9,0),"""")"

Excel vba variable not defined when using range variable

I have function testFunc that takes Range as an argument, loops thorugh its cells and edits them. I have sub testSub that tests two cases: first is when I pass the current workbook's range to testFunc through: 1. variable Range 2. just as an argument testFunct(...Range("A1:A16")).
The second case is when I open another workbook and do the same - pass one of its worksheets range to the testFunc directly or via variable.
Function testFunc(aCol As Range)
Dim i As Integer
i = 0
For Each cell In aCol
MsgBox (cell.Value)
cell.Value = i
i = i + 1
Next
testFunc = i
End Function
Sub testSub()
Dim origWorkbook As Workbook
Set origWorkbook = ActiveWorkbook
Dim aRange As Range
Set aRange = ThisWorkbook.Sheets("sheet 1").Range("A1:A16")
Dim dataWorkbook As Workbook
Set dataWorkbook = Application.Workbooks.Open("Y:\vba\test_reserves\test_data\0503317-3_FO_001-2582480.XLS")
Dim incomesNamesRange As Range
Set incomesNamesRange = dataWorkbook.Worksheets("sheet 1").Range("A1:A20")
' origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(dataWorkbook.Sheets("1").Range("A1:A20"))
origWorkbook.Worksheets("Ëèñò2").Cells(1, 50) = testFunc(incomesNamesRange)
' testFunc aRange
'origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(aRange) '<---good
' origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(ThisWorkbook.Sheets("sheet 1").Range("A1:A16"))
End Sub
The problem is, as I indicated with comments, when I open a foreign workbook and pass its range through a variable it gives an error variable not definedFor Each cell In aCol`, while all other cases (including passing range variable of the current workbook) work fine.
I need testFunc to stay a Function, because it's a simplfied example of some code from bigger program which needs to take a returned value from a function. And I need to store that Range in a variable too, to minimize time of the execution.
EDIT: As pointed out in the comments, I replaced Cells(1,5) with origWorkbook.Worksheet("shee t1").Cells(1,5) and fixed variable name, but the original mistake changed to variable not defined. I edited the title and body of the question.
The default name for the worksheet shouldn't have a space in it.
Set incomesNamesRange = dataWorkbook.Worksheets("sheet 1").Range("A1:A20")
Change this to:
Set incomesNamesRange = dataWorkbook.Worksheets("Sheet1").Range("A1:A20")
And see if that fixes it.

To modify INDEX-MATCH which is not working

Basically this is supposed to be a modified INDEX/MATCH formula but will depend on variables and headers on another workbook, as well as hopefully make it easier on the user by only requiring them to provide two parameters.
Option Compare Text
Function DATAFILL(ID_number, source_headerRow) As Variant
ID_header_name = Cells.Item(1, ID_number.column).Value
Dim wb As String, ws As String
Dim ID_src As Range
'check if source_headerRow is an external workbook
If source_headerRow Like "'" Then
src = Split(source_headerRow.address(External:=True), "!")(0)
wb = Replace(Split(src, "]")(0),"[","")
ws = Split(src, "]")(1)
id_col = Application.WorksheetFunction.Match(ID_header_name, source, 0)
Set ID_src = Workbooks(wb).Worksheets(ws).Range(Cells(1, id_col))
Else
Set ID_src = Range(Cells(1, Application.WorksheetFunction.Match(ID_header_name, source_headerRow, 0)))
End If
headername = "Shift" 'placeholder
Set addr = Workbooks(wb).Range("A:Z")
DATAFILL = Application.WorksheetFunction.Index(addr, Application.WorksheetFunction.Match(ID_number, ID_src), Application.WorksheetFunction.Match(headername, source_headerRow, 0))
End Function
I'm very new to VBA so I can't pinpoint exactly where I'm going wrong...
No matter what I do, I get #VALUE! error.
Or is there a way to make INDEX/MATCH user friendly without needing VBA/Macros?
You don't say what line is give you the VALUE error. That would help.
Or is it in a specific cell?
You haven't defined "addr" variable type anywhere that I can see
and you don't have OPTION EXPLICIT at the top, so by default "addr" wil be a Variant data type.
It needs to be Object at minimum and preferably Range
You should add Option Explicit to the top of your module (above Option Compare Text) and recompile until you can fix all the errors (if there are more)

VBA for Excel throws "Object variable or with block variable not set" when there is no Object

In my code, I have declared these variables:
Dim Field_Name, Datatype, row As Integer
Then, inside a For loop, I have this code:
Field_Name = Worksheets(i).UsedRange.Find("Field Name").Column
Datatype = Worksheets(i).UsedRange.Find("Datatype").Column
row = Worksheets(i).UsedRange.Find("Field Name").row + 1
However, that code throws the "Object variable or with block variable not set" run-time error. According to the API, the Range.Column and Range.row property is a read-only Long. I have tried making the datatype of my variables to Long, but with no success. It would appear that VBA expecting me to do
Set Field_Name = Worksheets(i).UsedRange.Find("Field Name").Column
Set Datatype = Worksheets(i).UsedRange.Find("Datatype").Column
Set row = Worksheets(i).UsedRange.Find("Field Name").row + 1
However, said variables are not objects, so doing that throws the "Object required" compile error.
Any help with this would be greatly appreciated. If you're not sure about how to fix it, then any workarounds or alternative ways to get the column number and row number of a cell would be greatly appreciated.
Even though this is an old question, I'd like to say something too.
I had the same problem to get this error while using the .Find method. I came to this question and so others will do the same.
I found a simple solution to the problem:
When Find does not find the specified string it returns Nothing. Calling anything directly after Find will lead to this error. So, your .Column or .row will throw an error.
In my case I wanted an Offset of the found cell and solved it this way:
Set result = Worksheets(i).Range("A:A").Find(string)
If result Is Nothing Then
'some code here
ElseIf IsEmpty(result.Offset(0, 2)) Then
'some code here
Else
'some code here
End If
Simplified answer:
Your .Find call is throwing the error.
Simply adding "Set " to that line will address the problem. i.e...
Set Datatype = Worksheets(i).UsedRange.Find("Datatype").Column
Without "Set," you are attempting to assign "nothing" to a variable. "Nothing" can only be assigned to an object.
You can stop reading here unless you would like to understand what all the other (valid, worthwhile) fuss was about your code.
To paraphrase all of the (warranted) code critiquing, your Dim statement is bad. The first two variables are not being "typed" and end up as variants. Ironically, this is why the solution I just described works.
If you do decide to clean up that Dim statement, declare DataType as a variant...
Dim DataType as variant
What about the below code:
For i = 1 to 1 ' change to the number of sheets in the workbook
Set oLookin1 = Worksheets(i).UsedRange
sLookFor1 = "Field Name"
Set oFound1 = oLookin1.Find(What:=sLookFor1, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
If Not oFound1 Is Nothing Then
Field_Name = oFound1.Column
RRow = oFound1.Row +1
' code goes here
Else
Msgbox "Field Name was not found in Sheet #" & i
End If
Set oLookin2 = Worksheets(i).UsedRange
sLookFor2 = "Datatype"
Set oFound2 = oLookin2.Find(What:=sLookFor2, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
If Not oFound2 Is Nothing Then
DataType = oFound2.Column
' code goes here
Else
Msgbox "Datatype was not found in Sheet #" & i
End If
Next i
This is an old old post - but I ran across it when I was having trouble figuring out why I suddenly could not import a PDF export into my excel sheet.
For me the problem was a row I was trying to match on was merged - did a simple unmerge for the entire sheet first and it worked like a charm.
'////// Select and open file
FieldFileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*") 'pick the file
Set frBook = Workbooks.Open(FieldFileName, UpdateLinks:=0, ReadOnly:=True, AddToMru:=False)
For Each mySheet In frBook.Worksheets
mySheet.Cells.UnMerge
Next mySheet

Different Results with Different PCs: Run Time Error 91 Object Variable or With Block Not Set

I run the code below in two different PCs while get two different result: one works fine, another reminds "run time error 91 object variable or with block not set". Can anybody help me out?
Function FindArchiveFile() As String
FindArchiveFile = Application.Intersect(Worksheets("Filelist").UsedRange, _
Worksheets("Filelist").Range("B:B")).Find( _
CDate(WorksheetFunction.Large(Workshee‌​ts("Filelist").Range("B:B"), 2))).Offset(0, -1).Value
Worksheets("Setting").Range("LastDate").Value = _
Application.Intersect(Worksheets("Filelist").UsedRange, _
Worksheets("Filelist").Range("B:B")).Find( _
CDate(WorksheetFunction.Large(Workshee‌ts("Filelist").Range("B:B"), 2))).Value
End Function
I've revised your function to make it more human-readable. This should work with some caveats.
If you are calling this function from a worksheet, it is unlikely to work.
This is because a workhseet function can generally only return a value to the calling cell. It cannot otherwise manipulate the worksheet objects. This function is trying to set a value in a named range "LastDate" and this is likely to fail. It may fail silently on this line and still return the value to the calling cell.
This function when called from a worksheet will likely raise a Circular Reference Error
When called from a subroutine, this function appears to work, or at least it does not return an error for me.
Sub Test()
'Use this to test the function
MsgBox FindArchiveFile
Worksheets("Setting").Range("LastDate").Value = FindArchiveFile
End Sub
Function FindArchiveFile() As String
Dim ws As Worksheet
Dim rngB As Range
Dim rngInt As Range
Dim foundVal As String
Set ws = Worksheets("Filelist")
Set rngB = ws.Range("B:B")
Set rngInt = Application.Intersect(ws.UsedRange, rngB)
foundVal = rngInt.Find( _
CDate(WorksheetFunction.Large(rngB, 2))).Offset(0, -1).Value
'## I comment the next line out and put it in the calling subroutine, since
' the function returns a value, use the function properly.
'Worksheets("Setting").Range("LastDate").Value = foundVal
FindArchiveFile = IIf(foundVal = vbNullString, "Not Found", foundVal)
End Function