Giving formula to a cell which has Unknown Range [ERROR] - excel

I'm basically trying to give a formula to a cell including unknown range. But I'm keep getting error. "inpt1" changes according to inpt1's count so I cannot formulate that. As inpt1 changes I cannot control the sum formula due to its range changes as well. Let me illustrate;
Cells(inpt1 + 3, 4).Formula = "=SUM(" & Range(Cells(3, 9), Cells(inpt1 + 2, 9)) & ")"
I added an example image for you guys to understand it better.
Try to sum the prices of I3:I5 & write it as a formula in green area in the picture

Can you try this:
Cells(inpt1 + 3, 4).Formula = "=SUM(I9:I" & inpt1 + 2 & ")"
Good luck

You need to return a string to the Formula.
Currently:
Range(Cells(3, 9), Cells(inpt1 + 2, 9))
Is trying to return a variant array to the formula string. A variant array cannot be converted to a string.
You want the address string. To get that we add .Address to the end of the Range:
Range(Cells(3, 9), Cells(inpt1 + 2, 9)).Address

Related

Cannot change the format after concatenating dates in Excel VBA

I have dates formatted as text. I want to change these dates' format from
"dd.mm.yyyy hh:mm" to "yyyy.mm.dd". (eg. "04.05.2020 10:33" to "2020.05.04") I use the following code (the original dates are in column "K"):
Dim cell As Range
For Each cell In Range(Range("K2"), Range("K2").End(xlDown))
cell.Offset(0, 7).Value = Mid(cell.Value, 7, 4) & "." & Mid(cell.Value, 4, 3) & Left(cell.Value, 2)
Next
The newly created dates cannot be formatted, though and so when I try to use a vlookup function on them, the function fails, saying it couldn't find the value in the lookup table. (dates are ok in the lookup table)
I need to manually enter every cell and hit enter and only after that will excel start recognizing the format.
I also found that if I use the manual "replace" function of excel like this: https://i.stack.imgur.com/U3k5e.png, and replace the dots with dots, excel will once again start to recognize the format, however it won't recognize any format when I use the following code:
Range(Range("R2"), Range("R2").End(xlDown)).Replace What:=".", Replacement:=",", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
Can someone help? How can I convert the format of these concatenated values in vba so that vlookup will recognize them?
Thanks!
Try this:
cell.Offset(0, 7).Value = Format(Mid(cell.Value, 7, 4) & " " & Mid(cell.Value, 4, 3) & " " & Left(cell.Value, 2), "yyyy.mm.dd")
The yyyy.mm.dd at the end tells it how you want it formatted. You also need to use a space or a slash (/) between the 3 functions because it doesn't recognize a period as a separator for it.
For example formatting the month. Take January:
m = 1
mm = 01
mmm = Jan
mmmm = January
Edit:
The only way I could see really doing it then is:
Dim cell as range
For Each Cell in Range(Range("K2"), Range("K2").End(xlDown))
Cell.Value = Format(Replace(Cell.Value,".","/"), "yyyy.mm.dd")
Next
Convert Date & Time As String to Date
Option Explicit
Sub createDate()
Dim Data As Variant
Dim currString As String
Dim currDate As Date
Dim i As Long
With Range(Range("K2"), Range("K2").End(xlDown))
Data = .Value
For i = 1 To UBound(Data, 1)
currString = Data(i, 1)
currDate = DateSerial(CLng(Mid(currString, 7, 4)), _
CLng(Mid(currString, 4, 2)), CLng(Left(currString, 2)))
Data(i, 1) = currDate
Next i
With .Offset(, 7)
.Value = Data
.NumberFormat = "yyyy.mm.dd"
'.Columns.AutoFit
End With
End With
End Sub
I ended up using the following code:
For Each cell In Range(Range("K2"), Range("K2").End(xlDown))
cell.Offset(0, 7).Value = Mid(cell.Value, 7, 4) & "/" & Mid(cell.Value, 4, 2) & "/" & Left(cell.Value, 2)
Next
Turns out I just had to use slashes to separate the concatenated parts, this allowed me to freely change the formatting of the newly created dates.
Special thanks to Simon, his answers helped a lot!

get the differences between 2 Integer columns into third column

I have to calculate the difference between the values of 2 columns(firstCol and lastCol) and set those differences in a different column(NextColumn). The row count keeps changing, so I have to calculate the rowCount before calculating the difference. I'm trying to write a loop using Range so that the difference can be calculated but it doesn't seem to work.
For i = 3 To lastRow
Range(Cells(3, NextColumn), Cells(lastRow, NextColumn)).FormulaR1C1 = "=Range(Cells(i, firstCol),Cells(i,firstCol)).Value - Range(Cells(i, lastCol),Cells(i,lastCol)).Value"
Next i
Any help would be greatly appreciated!
Thank you
Nick
For any input of "i" into the formula, you need to use " & i & " when using using a formula="", such as:
"=A" & i & "+B" & i
When you change to just a formula that doesn't input a formula to the cell (math happens in VBA), you can ignore the Excel formatting and "" blocking, such as:
= Cells(i,"A").Value + Cells(i,"B").Value
Make sure to use your loop variable where appropriate, so that you would have an outcome in a loop like:
Dim i as Long
For i = 1 to 10
Cells(i,"C").Formula = Cells(i,"A").Value + Cells(i,"B").Value
Next i
Why looping ? Unless I misunderstood the question, something like this should do the trick:
Range("X3:X"& lastrow).Formula = "=C3-D3"
The formula will adjust.
vba needs to be outside the quotes and you do not need the loop:
Range(Cells(3, NextColumn), Cells(lastRow, NextColumn)).Formula = "=" & Cells(3, firstCol).Address(0, 0) & "-" & Cells(3, lastCol).Address(0, 0)
No loop needed. Excel will change the relative references as needed.

Calculating Cell Addresses in Formula with Row() and Column() in MS Excel VBA

I have gotten so much excellent help from this site. This is my first question. I have googled all the wordings I can think of and looked at all possible related threads on this site and others, and cannot find an explanation.
I am trying to automate a sheet into which a data table of variable size will be pasted.
Here is the formula I am trying to replicate:
=(C26-B26)/B26 (percent variation to previous month)
Edited to respond to a comment: This formula is in cell C28 in the sheet I am being asked to automate. So it is referring to cells two rows above and 1 column to the left of the cell where the formula is located.
Here is my code which the editor accepts:
ActiveCell.Formula = "=(" & (Cells(Index(Row() - 2), Index(Col())).Address(False, False)) & "-" & Cells(Index(Row() - 2), Index(Col() - 1)).Address(False, False) & "/" & Cells(Index(Row() - 2), Index(Col() - 1)).Address(False, False) & ")"
When I run this, I get a compile error: Sub or Function not defined and the first instance of row is highlighted.
It seems to me I read somewhere that one cannot calculate with Row() and Column() but I have not been able to find that again. I have found many examples online of people using Row() and Column() in this way to find cells adjacent to the active cell.
I appreciate any help and suggestions.
Thank you in advance.
I'd determine the indices of your reference cell (the one that's not known). In the example below, I'm simply using the indices and converting them to characters from ASCII and concatenating the returned character and the row number.
Dim activeRow, activeColumn As Integer
activeRow = 40 'Iterate through or use Range reference as Range.Row
activeColumn = 3 'Iterate through or use Range reference as Range.Column
MsgBox ("=(" & Chr(64 + activeColumn) & (activeRow - 2) & "-" & Chr(64 + activeColumn - 1) & (activeRow - 2) & "/" & Chr(64 + activeColumn - 1) & (activeRow - 2) & ")")
Update:
Also take a look at this question for referencing the instance of the calling cell in a Public Function, specifically Fionnuala's answer.

Concatenating SumIfs in VBA

I'm trying to get this segment of code to execute. This is a simplified version of the code. I've included the relevant code. I'm trying to concatenate strings and named ranges into a SumIfs formula, but I get error 1004 "Application-defined or Object-defined error." I have a working line of code above this problem section that is similar with the exception of doing a sum function, instead of sumif. Any idea how to get this code to execute? Thank you.
Dim wb As Workbook
Dim ara As Worksheet
Dim inv As Worksheet
Dim ARBlock As Range
Dim Invoices As Range
Dim AgedDays As Range
Set wb = ThisWorkbook
Set ara = wb.Sheets("AR Aging")
Set inv = wb.Sheets("Invoices")
Set ARBlock = ara.Range("a6")
Set Invoices = inv.Range("a6", inv.Range("a6").End(xlDown))
Set AgedDays = Invoices.Offset(0, 6)
'Populate A/R age buckets
For i = 6 To ARBlock.Rows.Count + 6
With ARBlock(i - 5, 1).Offset(0, 3)
.Value = "=SumIfs(" & Invoices.Offset(0, 4).Address & "," & _
Invoices.Address & "," & ARBlock(i - 5, 1).Value & "," & _
Invoices.Offset(0, 6).Address & ","" <= "" & &O30)"
End With
Next i
End Sub
The line beginning with ".value" is where I'm getting the error message. P.S.: I need the cell to contain the concatenated formula, as opposed to the output value.
UPDATE 1:
As some suggested I updated the .value line to:
.Offset(0, 3).Formula = "=SumIfs(Invoices.Offset(0, 4).Address,Invoices.Address,ARBlock.cells(i - 5, 1).Value)"
I'm still getting the same error. Some auditing I've done:
Removing the "=" before "Sumifs" allows the code to run fine; pasting in the formula into the target cell as text. In this form, my output for i=1 goes to ARBlock.cells(1,1), as it should.
I also used Debug.Print to view all of the components of the formula:
Debug.Print ARBlock.Cells(i - 5, 1).Address
'output $A$6
Debug.Print ARBlock.Cells(i - 5, 1).Value
' output International Business Machines
Debug.Print Invoices.Offset(0, 4).Address
'output $E$6:$E$255
Debug.Print Invoices.Address
'output $A$6:$A$255
I suspected the issue might be that the range dimensions might have been off, but this is not the case. My next suspicion is that the output International Business Machines needs to be in " " for the formula to read it correctly. I hardcoded in
""International Business Machines""
to see if this would fix the formula, but I keep getting the same error once I add the "=" back in. The formula syntax is correct, the dimensions are the same between the sum range and criteria range. Anyone else have any ideas?
.Offset(0, 3).Formula = "=SumIfs(Invoices.Offset(0, 4).Address,Invoices.Address,ARBlock.cells(i - 5, 1).Value)"
Change to:
.Offset(0, 3).Formula = "=SumIfs(" & Invoices.Offset(0, 4).Address & ", " & Invoices.Address & ", " & chr(34) & ARBlock.Cells(i - 5, 1).Value & chr(34) & ")"
EDIT: Added quotes chr(34) around your string!
Your ARBlock(i - 5, 1).Value most likely is an empty cell, which messes the SUMIFS formula as it builds it with to consecutive commas

Excel Countif in a macro

My countif function works fine in the excel sheet itself as shown below
=COUNTIF(F111506:K111519,">0")
I however do not get the same results when executing this in a macro. Stepping through the macro, I do the see the correct range highlighted.
nonZeroCount = Application.CountIf(Range(("F" & curRow + 5), ("K" & curRow + 18)).Select, ">0")
I always get a value of 0. Can anybody suggest what I am doing wrong?
thanks
Use this one:
nonZeroCount = Application.CountIf(ThisWorkbook.Worksheets("shName").Range("F" & curRow + 5 & ":K" & curRow + 18), ">0")
where shName relevant sheet name.
Or another way:
With ThisWorkbook.Worksheets("shName")
nonZeroCount = Application.CountIf(.Range(.Cells(curRow + 5, "F"), .Cells(curRow + 18, "K")), ">0")
End With
Maybe use the Evaluate command:
FormulaResultCount = Evaluate("CountA(C:C)")
Replace the stuff in quotes with your formula.
Another way to get your desired result is
nonZeroCount = WorksheetFunction.CountIf(Range("F" & curRow + 5, "K" & curRow + 18), ">0")

Resources