VBA sort function not working - vba

The following is an excerpt from a larger section of VBA code. I'm having a problem sorting a list of values after I paste them from another sheet. The list of values are successfully pasted and are selected before the sorting should be happening. Also the sorting code which I'm using works fine if it's used seperately in a macro by itself. Any suggestions as to what may be going wrong here? Thanks
Dim ProductType As String
Dim ValueDate As String
ProductType = Range("I19").value
ValueDate = Range("I18").value
ActiveSheet.name = ProductType & " " & ValueDate
Sheets("SensitivityResults").Cells(6, 1).Resize(653).Copy
Sheets(ProductType & " " & ValueDate).Range("A3").PasteSpecial Paste:=xlValues
Selection.Sort Key1:=Range("A3"), Order1:=xlAscending, Header:=xlGuess

selection might not be set properly, try with
Sheets(ProductType & " " & ValueDate).Range("A3:A656").Sort Key1:=Range("A3"), Order1:=xlAscending, Header:=xlGuess

Related

Linking cells to different worksheet by using vba to insert dynamic formulas

I am creating a new worksheet called varRef and am trying to link cells of an existing worksheet to this new worksheet by using VBA. I have been trying to solve it for a couple of hours but cannot get it right and cannot find a similar case on the web either.
The code is:
Dim varRef as Variant 'name of the new sheet
varRef = Inputbox("xyz") 'this is how I define the name
Dim intRow As Integer 'row that corresponds to the appropriate postion in the existing sheet
intRow = ActiveCell.Row 'see above
Cells(intRow, 22).Formula = "=IF(varRef & ""!I148""="""","""",varRef & _
""!I148"")" 'trying to link the contents within the same workbook
The result in the cell I get is
=IF(varRef & "!I148"="","",varRef & "!I148"
which is obviously not working.
Issue 1) is that VBA does not recognize my variable in the formula. It is working for naming the sheet however.
Issue 2) is the quotation marks, that are not working as intended. One is supposed to use double quotation marks to not end the string. However the second marks will not disappear in the final code of the cell.
Any help is very much appreciated and hopefully valuable for other users as well!
You had some count issues with hoe many " you have before and after the varRef variable.
Also, I prefer to use Chr(34) to have " inside the Formula string, this way I don't get confused with how many " I need to use.
Try the code below:
Cells(intRow, 22).Formula = "=IF(" & varRef & "!I148=" & Chr(34) & Chr(34) & "," _
& Chr(34) & Chr(34) & "," & varRef & "!I148)"

VBA Set Cell value to text containing ' not working

I'm trying to get a macro to type out a heap of formulae for me. The formula goes something like this:
=COUNTIF('other_sheet'!A:A,"hello*")
The user can specify A and other_sheet, so I select the cell and then go
ActiveCell.Value = "=COUNTIF('" & othercell & "'!" & column & ":" & _
column & """,hello*"")"
But it keeps giving me errors like:
1004: Object Defined Error
I have tried using ActiveCell.Text, ActiveCell.Formula etc. and they all don't work.
It needs to be ActiveCell.Formula and ", is the wrong way around next to Hello. It should be:
ActiveCell.Formula= "=COUNTIF('" & othercell & "'!" & column _
& ":" & column & ",""hello*"")"
Apparently you can only put proper, completed answers into a cell.
i.e. if the output turns out to be "=sum(A:A" and a bracket isn't closed, then the application throws an error just as if you typed it in manually.

Run-time error '1004' when applying formula to Range.FormulaR1C1 in VBA

I'm trying to apply a big nested formula to a range using the code below. Basically, if the value in cell A of the active row exists in the column A of another workbook and if the cell in column E of the active row is not empty, I want the active cell to display the cells to display the value of the equivalent cell in a separate workbook.
This needs to be applied to several worksheets so I'm using the variables lrow (which is an int with the last row of the active worksheet in workbook#1) and tlrow (which is an int equal to the last row of the active worksheet in workbook#2). When I step through the sub, these variables both return the numbers I would expect them to.
Likewise, this is inside of a for loop so I also use Worksheets(i).Name where I is an int.
When I run the code, I get the run-time error "'1004': Application-defined or object-defined error".
I'm assuming it's a syntax issue.
Code:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IF(ISERROR(VLOOKUP(RC1,'[temp.xlsx]" & _
Worksheets(i).Name & _
"'!A15:D" & tlrow & ",3,FALSE)),""0"",VLOOKUP(RC1,'[temp.xlsx]" & _
Worksheets(i).Name & "'!A15:D" & tlrow & ",3,FALSE))))"
Try using this:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IF(ISERROR(VLOOKUP(RC1," & _
Worksheets(i).Range("A1:D" & lrow).Address(ReferenceStyle:=xlR1C1, External:=True) & _
",3,FALSE)),""0"",VLOOKUP(RC1," & _
Worksheets(i)..Range("A1:D" & tlrow).Address(ReferenceStyle:=xlR1C1, External:=True) & _
",3,FALSE)))"
What version of Excel are you running? In more recent versions you can use the Iferror function in this formula to really chop down the size.
It would be something like this:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IFERROR(VLOOKUP(RC1," & " & Worksheets(i).Range("A1:D" & _
tlrow).Address(ReferenceStyle:=xlR1C1, External:=True) & ",3,0),""0"")"
Thanks for your help. I was able to resolve the problem by defining my vlookup range in a Range variable and then inputting the variable name in L42's equation in place of
worksheets(i).Range("A1:D" & lrow)
Really apprecaite the responses! Thanks again.

Creating a textbox to trigger a VBA formula

Recently I created Macros which searched through column B using a text match and populated column H with "Y" or "N" depending on whether there was a match or not. The code used was as follows.
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
.Range("H2:H" & lRow).FormulaR1C1 = "=IF(C[-6] = ""Commodities Ags/Softs"", " & _
"(IF(RC[-3]=R1C24,""Y"",(IF(RC[-3]=R2C24,""Y""," & _
"(IF(RC[-3]=R3C24,""Y"",(IF(RC[-3]=R4C24,""Y""," & _
"(IF(RC[-3]=R5C24,""Y"",(IF(RC[-3]=R6C24,""Y""," & _
"(IF(RC[-3]=R7C24,""Y"",(IF(RC[-3]=R8C24,""Y""," & _
"(IF(RC[-3]=R9C24,""Y"",""N"")))))))))))))))))),"""")"
Range("H2:H" & lRow).Select
Selection.Copy
ActiveSheet.Range("H2:H" & lRow).PasteSpecial xlPasteValues
I had to write 7 different macros because of the 7 possible matching texts in column B and the data I was matching it to comes from 7 different sources. I.E. If I received data from Commodities Ags/Softs, I would run the Commodities Ags/Softs macro (the other macros are identical, just swapping the text).
Now I've been told the data will be expanding to 70 different sources with 70 potential matching texts, rendering my specific macro to specific data approach pretty useless.
I was wondering if anyone knows how I could generalise the macro and in doing so, create a textbox which would tell the macro what text to match in column B.
Basically, I was hoping that if I received data from a particular source, I could run the macro, a textbox would appear in excel and whatever I typed into it would be the text I'm trying to match in column B, effectively altering the generalised macro.
Any help would be greatly appreciated, I'm new to VBA,
Cheers!
Basically:
Dim sMatch as String
sMatch = InputBox("Enter match data")
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
With .Range("H2:H" & lRow)
.FormulaR1C1 = "=IF(C[-6] = """ & sMatch & """, " & _
"(IF(RC[-3]=R1C24,""Y"",(IF(RC[-3]=R2C24,""Y""," & _
"(IF(RC[-3]=R3C24,""Y"",(IF(RC[-3]=R4C24,""Y""," & _
"(IF(RC[-3]=R5C24,""Y"",(IF(RC[-3]=R6C24,""Y""," & _
"(IF(RC[-3]=R7C24,""Y"",(IF(RC[-3]=R8C24,""Y""," & _
"(IF(RC[-3]=R9C24,""Y"",""N"")))))))))))))))))),"""")"
.Value = .Value
End With

Insert formula from VBA

I'm attempting to have the following code insert the formula into the changed cell. I'm not receiving any errors but the code is not populating on the worksheet. Any insight into what I'm not doing?
formula_p1 = _
"=GETPIVOTDATA(""Max of " & [value_column_header] & ",Database!R1C14, & _
""Key"",& Key &)"
Debug.Print Cell.Address
Sheets("Cost Sheet").Cell.Formula = formula_p1
Thank you in advance.
Update
My current code is below I'm stuck on the concatenation in the final part. I'm not sure how to accomplish this in VBA. Also I need this to be a formula that will re evaluate on changes to the "Family" part that can be done on the worksheet. The change in "Family" is accomplished from a combo box selection.
formula_1 = _
"=GETPIVOTDATA(""Max of " & value_column_header & """,Database!$N$1,""Key""," & Concatenate(CurrentHFMFamily, G5, Left(B12, 4)) & ")"
This is the final result of what i was trying accomplish. It's not pretty but it's quick and stable.
=IF(INDIRECT(CONCATENATE("B",ROW()))=""," ",IFERROR(GETPIVOTDATA("Max of & _
"&INDIRECT((ADDRESS(11,COLUMN())))&"_ADJ",Database!R1C14,"Key",& _
LEFT(INDIRECT(CONCATENATE("B",SUM(ROW()-1))),4)&CurrentHFMFamily& & _
(OFFSET(INDIRECT(ADDRESS(ROW(),COLUMN())),-(SUM(ROW()-(5))),- & _
(MOD(COLUMN()+1,4))))),0))
Thanks to everyone for your ideas they helped in pointing me in the right direction.