Match function in VBA code - vba

I'm trying to perform the following task using VBA: find a cell in table head that contains "Total number" title, return its column number, then find a cell on the intersection of raw with given number and column with returned number, and finally assign the value from this cell to a variable. Then wrote the value of this variable to another cell.
For example, suppose that the title "Total number" is in the AL column, then I'm trying to assign x = AL177 and then AM173 = x.
In a fact it is just a small part of more complex task, but unfortunately I can't deal with this fraction.
I wrote
Sub script()
Dim x As Integer
x = Cells(177, Application.WorksheetFunction.Match("Total number", ActiveWorkbook.Sheets("sheet name").Range("2:2")))
Worksheet("sheet name").Range("AM173").Value = x
End Sub
I need to specify sheet name exactly (not just active sheet or something else) since some time later I'm going to execute it from another sheet.
When I try to run it Excel gives me an error:
"Compile error: Sub or Function not defined"
Can anyone explain what is wrong with my code and how it should be done?

Related

Referencing indirect cells in excel VBA

So I am trying to have a cell reference in my code be an indirect reference. For instance I want to update the value in column B cell "X" where X is defined in cell B1.
Here is the code that I am currently trying but I keep getting an out of range exception. I am very new to VBA so my syntax could just be very far off.
Workbooks("Personal_Finances").Sheets(categoryType).Range("$B($B$1)").Value = ammount
Try,
with Workbooks("Personal_Finances").Sheets(categoryType)
.cells(.Range("B1").Value, "B") = ammount
'alternate
.Range("B" & .Range("B1").Value) = ammount
end with
Here .Range("B1").Value is used for the row reference in .Cells. The alternate is closer to what you were originally attempting.
I've wrapped the working code in a With ... End With block to maintain the parent worksheet reference.
There is no need for $ in a quoted string cell reference unless used in a formula populating multiple cells at once.
def a new variable and assign the value of cell $b$1 to it.
dim temp_row as integer
temp_row.value =Workbooks("Personal_Finances").Sheets("categoryType").Range("B1").Value
Workbooks("Personal_Finances").Sheets(categoryType).Range("$B" & temp_row).Value = amount
or just do the same thing in one line.
Or:
With Workbooks("Personal_Finances").Sheets(categoryType).Range("B1")
.Offset(.Value2 - 1) = ammount
End With
Where the “With ... End With” block references cell B1 of wanted worksheet in wanted workbook and the nested statement offsets it by its value minus one (to reach wanted row)

Excel VBA Compare cell value to list and overwrite value in separate sheet

In a workbook I have, users either manually enter an account code or select one from a list and the account codes are placed in column C (C7:C446) in a sheet called "JE". The account codes look like this ####### - ### - ## - ######. In column D (D7:D446) in sheet "JE", there is a formula that captures the last 6 digits of the account code. In a sheet called "required_refs", there is a list of 6 digit codes in column A. If the value in the D column in sheet "JE" equals any of the values in column A of "required_refs" sheet, I would like the value in the D column cell to overwrite the cell value in cell D1 in a separate sheet called "references" (I know that may have been confusing, sorry)
Example: if the value of D25 matches any of the values listed in column A of sheet "required_refs", upon double clicking a red colored F25 cell, put the value of D25 (of sheet "JE"), and put it in cell D1 on sheet "references".
I've taken a crack at it as best I know how. I've placed this code in sheet JE:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim project As Range: Set project = Range("D7:D446")
Dim param As Range: Set param = Worksheets("references").Range("D1").Value
For Each cell In project
If project.Value = Worksheets("required_refs").Range("A:A").Value Then
Call gotoRef_ 'macro that simply selects/navigates to the required_ref sheet
project.Value = param
End If
End Sub
Thanks so much in advance for any suggestions on how to complete this. I can elaborate on this further if needed.
This will do what you want:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Intersect(Target, Range("F7:F446")) Is Nothing Then Exit Sub
Dim varReference As Variant
varReference = Columns("D").Cells(Target.Row).Value2
If Not IsError(Application.Match(varReference, Worksheets("required_refs").Columns("A"), 0)) Then
Worksheets("references").Range("D1").Value = varReference
End If
End Sub
Important Points:
Whenever working with event handlers, always limit the scope of the target range in the first line. Otherwise, it might not work correctly or it could slow done your spreadsheet.
Make sure your JE sheet column D values and required_refs sheet column A values are all either text or numbers. Otherwise the values won't be compared correctly.
Note the usage of Application.Match() instead of WorksheetFunction.Match() to access the worksheet function. This, coupled with the use of a Variant type variable, allows us to trap the error that occurs if the match fails.
You can always do this on the sheet. Consider the MATCH function. See here for how to use MATCH.
Or another great tool if you're searching for something in a table associated with a value in another column (not your case I don't think)--VLOOKUP formula. Place this formula in the D cell of the sheet you want to place the numbers in. VLOOKUP is in the following format:
=vlookup(lookup value,table_array,column index number, [range lookup])
The lookup value is the 6 digit code you're looking for (on the JE sheet)
The table_array is simply selecting the values you want to search for (required_refs sheet)
The column index number would be one, since the table only has 1 column. It's basically the column number of the value you're looking for.
And range lookup is for if you think there might be more than one place where it matches.
For your case I think it would look like this:
=vlookup('JE'!D1,'required_refs'!A1:A,1,FALSE)
Then just lock the values you want to keep and click and drag down.
Explanation for VLOOKUP here

Excel Summing over Rows with for loop - Type mismatch error

so I am currently working on an Excel sheet where I have to calculate confidence intervals. Long story short, I think the only way I can do this automatically, is to write vba code. The first step would be to calculate the average of the cells in a column for several columns in the sheet. What I did:
Dim temp As Double
temp = 0
Dim it_row As Long
for it_row = 1 to 100
if IsBlank(Sheet.Cells(it_row,it_col)) then
temp = temp + 0
else
temp = temp + Sheet.Cells(it_row,it_col).Value
end if
next it_row
Dim Average As Double
Average = temp/100
'writing average in another cell
This code does not work, as the compiler returns Type missmatch, error code 13
in the line
temp = temp + Sheet.Cells(it_row,it_col).Value
I tried to do a CDouble(Sheet.Cells(it_row,it_col).Value) but that did not work.
Any help is appreciated, as I am quite desperate because googling did not really help me.
I should mention that I do have to use vba and this code because this is part of a bigger automated process and my supervisor said I must use vba for automation in the next step.
The Average and Sum Excel Functions ignore text, boolean, and empty values:
Average = Application.Average(Sheet.Cells(1, it_col).Resize(100))
Check
Sheet.Cells(it_row,it_col).Value
...with
if isnumeric(Sheet.Cells(it_row,it_col).Value)
...before adding it to a double type value. If that check fails, then you can chose to skip it or treat it as sth. else.
I would've added this as a comment, but I don't have enough rep. to add comments.

Getting Type mismatch Error in VBA

I have a code, something like this :
Public Sub Match()
ThisWorkbook.Sheets("Sheet1").Activate
Range("Data!H8") = Application.Sum(Application.Index(Range("A:GH"), 0, Application.Match("ORDERS" & "Country", Range("B2:B100") & Range("A2:GH2"), 0)))
End Sub
When I run this code I'm getting a error "Type Mismatch". Can anybody help me with this?
enter image description here
What you are trying to do can be done. But its not simple because of the way your data is represented. Here is an example of how I was able to acheive your goal.
I used Column I as the country you are trying to sum.
- I3 I search for this country which returns the column number.
- I4 I convert this number to letter
- I5 Do the sumifs formula (using the indirect formula to tell it to use the found column (C in this example) as the sum column. Where column "A" = "orders"
Forumlas used are in column J.

Create VBA to autoassign type

I am a beginner in VBA programming.
Description: The left table is the 'reference table'
Objective: Fill up the 'Type' col of right table using macro
How: Write a macro that go through the 'reference table' comparing col E (Descript) with keyword. If the cell in col E contain a specific key word, col F will automatically be assigned a category
P.S: What are the recommended websites that provide tutorial? Something like codecademy
So still stuck at correctly referencing table:
thanks for editing your answer to include the code. Next time please copy/paste it, rather than using an image, so that we don't have to type it all out ourselves if we need to test what you've written! I can see where you're at now, and I feel this will work you for. Basically, you need to cycle through the rows rather than the columns.
Rather than using a subroutine, I think a function will work better for you. That way you can embed it in your table, rather than having to run a subroutine each time.
Function getCategory(strInput As String)
Dim tbl As ListObject
Dim x As Long
Set tbl = ActiveSheet.ListObjects("Table1")
For x = 1 To tbl.ListRows.Count
If InStr(strInput, tbl.ListRows(x).Range(x, 1)) Then
getCategory = tbl.ListRows(x).Range(x, 2)
Exit Function
End If
Next x
End Function
Then you can simply enter the formula in column F, e.g. in F2 enter
=getCategory(E2)
and copy/paste down for each row in your table.