I have a requirement where I need to write a formula dynamically using VBA.
I am able to find the Column Name and Row Number. Now how do I apply it in a formula ?
Colm = WorksheetFunction.Match("Name", Sheets("Sheet1").Rows(5), 0)
BuName = GetColumnName(Colm)
Row = WorksheetFunction.Match("Name", Sheets("Sheet1").Columns(Colm), 0)
The BuName returns a String which is "A". The Row Returns the number which is 2.
Now I tried to Apply it in a formula using VBA like this,
Worksheets("Sheet1").Range("AQ1").Formula = "=$'BuName'$Row&$A$10"
Does anyone Know how to write the formula for that?
This works for me:
Dim Colm, Row As Long
Dim BuName As String
With Worksheets("Sheet1")
Colm = WorksheetFunction.Match("Name", .Rows(5), 0)
BuName = GetColumnName(Colm)
Row = WorksheetFunction.Match("Name", .Columns(Colm), 0)
.Range("AQ1").Formula = "=$" & BuName & "$" & Row & "&$A$10"
End With
Related
I have a very simple question that I can't find the answer to.
Here is an example of what I'd like to do:
Sample Data
If a row in column A = 'Sandwiches', I would like column B to display 'It's a Sandwich'
If a row in column A = 'Wraps', I would like column B to display 'It's a Wrap'
etc. etc.
So far, I am able to do this for the first row. I'm having trouble creating a for loop to loop through all the available cells.
Here is what I have so far (was thinking of adding Else If statements for different values later):
Current If Statement
If you prefer the use of VBA code instead a formule as Ozgun Senyuva suggested. You can try this code:
Sub Food_and_thing()
Dim myLine As Double
Dim myFood As String
Set SavedData = Sheets("SavedData")
myLine = 2
With SavedData
Do While .Cells(myLine, 1) <> "" 'Assume that Category is in column A, and Generated Asset Name is in column B
myFood = " an other thing"
If .Cells(myLine, 1) = "Sandwiches" Then
myFood = " a Sandwich"
ElseIf .Cells(myLine, 1) = "Wraps" Then
myFood = " a Wrap"
ElseIf .Cells(myLine, 1) = "Salads" Then
myFood = " a salad"
End If
.Cells(myLine, 2) = "It's" & myFood
myLine = myLine + 1
Loop
End With
End Sub
Akash you do not need to write vba codes for this. You may use a lookup table and apply Vlookup formula as #BigBen said.
Apart from this, this formula can make you happy if you ignore some spelling errors. Enter this in cell B2 and paste along the way down.
="It's " & A2
I am trying to find the first row number that matches two criteria located in two columns and in an array in my code.
ex:
market = Array("market1", "market2", "market3"...)
report = Array("report1", "report2", "Report3"...)
rownumber = Application.Match(Range("B:B" & "L:L"), market(i) & report(z))
ws2.Range("N2").Value = rownumber
is there a way to do this? let me know if you need anything else
thanks in advance
This is an array formula and as such it cannot be done with Application.Match. You can use Evaluate.
market = Array("market1", "market2", "market3"...)
report = Array("report1", "report2", "Report3"...)
Dim rownumber As Variant
rownumber = ws2.Evaluate("IFERROR(Match(""" & market(0) & report(0) & """,B:B & L:L, 0),""Not Found"")")
ws2.Range("N2").Value = rownumber
If the search range is not found on ws2 change the ws2 in front of .Evaluate to the worksheet on which the data is found.
But when using array formulas one should not use full column references, try to find the extent of the data and reference just those cells.
I am trying to create a function or functions that can sum daily hours from time cards for each client to come up with the total hours worked per day. Each client has it's own sheet inside of a single workbook.
Currently, I have a function that determines the sheet that goes with the first client (the third sheet in the workbook):
Function FirstSheet()
Application.Volatile
FirstSheet = Sheets(3).Name
End Function
And one to find the last sheet:
Function LastSheet()
Application.Volatile
LastSheet = Sheets(Sheets.Count).Name
End Function
The part that I am having trouble with it getting these to work within the sum function.
=sum(FirstSheet():LastSheet()!A1
That is basically what I want to accomplish. I think the problem is that I don't know how to concatenate it without turning it into a string and it doesn't realize that it is sheet and cell references.
Any help would be greatly appreciated.
So, an example formula would look like this:
=SUM(Sheet2!A1:A5,Sheet3!A1:A5,Sheet4!A1:A5)
That would sum Sheet2-Sheet4, A1:A5 on all sheets.
Is there a reason you need to write the VBA code to do this?
Can't you just enter it as a formula once?
Also, if you're going to the trouble of writing VBA to generate a formula, it may make more sense to just do the sum entirely in VBA code.
If not, try this:
Sub GenerateTheFormula()
Dim x, Formula
Formula = "=SUM(" 'Formula begins with =SUM(
For x = 3 To Sheets.Count
Formula = Formula & Sheets(x).Name & "!A1," 'Add SheetName and Cell and Comma
Next x
Formula = Left(Formula, Len(Formula) - 1) & ")" 'Remove trailing comma and add parenthesis
Range("B1").Formula = Formula 'Where do you want to put this formula?
End Sub
Results:
The functions return strings and not actual worksheets. The Worksheet does not parse strings well. So add a third function that uses the Evaluate function:
Function MySum(rng As Range)
MySum = Application.Caller.Parent.Evaluate("SUM(" & FirstSheet & ":" & LastSheet & "!" & rng.Address & ")")
End Function
Then you would simply call it: MySum(A1)
It uses the other two function you already have created to create a string that can be evaluated as a formula.
I didn't understand ur question completely but As I understood u have different sheets of different clients which contains supoose column 1 date and column 2
contains hours on that particular date wise hours and a final sheet which column1 contains name of client and column 2 contains total hoursPlease try it
Sub countHours()
Dim last_Row As Integer
Dim sum As Double
sum = 0
'Because I know number of client
For i = 1 To 2 'i shows client particular sheet
last_Row = Range("A" & Rows.Count).End(xlUp).Row
Sheets(i).Activate
For j = 2 To last_Row
'In my Excel sheet column 1 contains dates and column 2 contains number of hours
sum = sum + Cells(j, 2)
'MsgBox sum
Next j
'Sheet 3 is my final sheet
ThisWorkbook.Sheets(3).Cells(i + 1, 2).Value = sum
sum = 0
Next i
End Sub
Happy Coding :
i am trying to insert a reference number into a cell in excel using vba. I want a prefix text of 'V0000' followed by an auto incremented number starting from 836.
so for each row that gets inserted I will have V0000836
Then V0000837
etc
A large portion of my code creates a new row and inserts data into it automatically one after the other, but instead of posting my whole code I am just wanting to focus on this one line of code which inserts value into column AA of my spreadsheet. I am using the following but it just gives me V00001 each time. can someone show me how I can get my code to do what I want it to.
ws2.Range("AA" & DestRow).Value = "V0000836" & Value + 1
Consider an alternative that does not remove numerical (mathematical) functionality from the cell's value.
ws2.Range("AA" & DestRow).numberformat = "\V0000000"
ws2.Range("AA" & DestRow).Value = 836 + 1
If you require the formatted (displayed) alphanumeric designation you can retrieve it like this.
Dim str as string, num as long
str = ws2.Range("AA" & DestRow).text '◄ V0000837
num = ws2.Range("AA" & DestRow).value '◄ 837
Using VBA, you can do this by incrementing the number each time the loop goes round and then prefixing the V0000 to the front like so:
Dim i As Integer
Dim cell As Range, rng As Range
Set rng = Range("A1:A10")
i = 836
For Each cell In rng
cell.Value = "V000" & i
i = i + 1
Next cell
I've got a workbook where I have one worksheet which contains a lot of data.
My goal is to create a macro that inserts a formula in a separate sheet to copy the data from the first sheet. Lets call the first sheet "Numbers1" and the second sheet "TidyNumbers1".
In the sheet "TidyNumbers1" I want to loop through each cell from column A to M and rows 1 to 60. So I've got a macro that so far looks like this:
Sub updateFormulasForNamedRange()
Dim row, col, fieldCount As Integer
colCount = 13
RowCount = 60
For col = 1 To colCount
For row = 1 To RowCount
Dim strColCharacter
If col > 26 Then
strColCharacter = Chr(Int((row - 1) / 26) + 64) & Chr(((row - 1) Mod 26) + 65)
Else
strColCharacter = Chr(row + 64)
End If
Worksheets("TidyNumbers1").Cells(row, col).Formula = "=IF(Numbers1!E" & col & "<>0;Numbers1!" & strColCharacter & row & ";"")"
Next row
Next col
End Sub
But the formula is supposed to looks like this for Column A, row 2:
IF(Numbers1!E2<>0;Numbers1!A2;"")"
And the formula in Column A, row 3 should look like this:
IF(Numbers1!E3<>0;Numbers1!A3;"")"
Formula in Column B, row 2 should look like this:
IF(Numbers1!E2<>0;Numbers1!B2;"")"
In other words, the formula looks to see if the value in Column E, row % is anything but 0 and copies it if conditions are met.
But, I see that I need to translate my integer variable Row with letters, because the formula probably needs "A" instead of 1. Also, I get a 1004 error (Application-defined or object-defined error) if I just try to use:
Worksheets("Numbers1").Cells(row, col).Formula = "=IF(Numbers1!E" & row & "<>0;Numbers1!" & col & row & ";"")"
I clearly see that the integer row should be translated to letters, if that's possible. Or if anyone has any other suggestions that might work. Also, the 1004 error is unclear to me why happens. I can define a string variable and set the exact same value to it, and there's no error. So it's probably the formula bar that whines about it I guess?
Here is a former post of mine containing functions for conversion of column numbers to letters and vice versa:
VBA Finding the next column based on an input value
EDIT: to your 1004 error: Try something like this:
=IF(Numbers1!E" & row & "<>0,Numbers1!A" & row & ","""")"
(use ; instead of ,, and "" for one quotation mark in a basic string, """" for two quotation marks).
Would not it be easier to get the cell address with the Cells.Address function?
For example:
MsgBox Cells(1, 5).Address
Shows "$E$1"
Best Regards