I have a question, I am trying to define a cell name in excel using vba. Now to select one cell only i have been using the following code which proves to work fine:
Range("A1").Name = "zm_1"
However I need to name a number of cells in a column i.e:
Range("A1").Name = "zm_1"
Range("A2").Name = "zm_2"
Range("A3").Name = "zm_3"
Range("A4").Name = "zm_4"
Since this is quite tedious for 100 cells, i have been trying to use an array:
For i=1 to 100
Range("A(i)").Name = "zm_(i)"
next
^ this however gives an error which i have been unable to track. Any ideas/suggestions on how can it be done? Thanks!
The problem is with Range("A(i)").Name = "zm_(i)" The " indicate that something is text, so you should place your (i) out of the ".
For the first part it is quiet easy, as you can also use the row and column way of describing the cell. Therefore that becomes
Range(Cells(i,1)).Name
For the second part you need to concatenate the text and the numbers. That becomes: "zm_" & i
You don't need an array, just your loop:
For i = 1 to 100
Range("A" & i).Name = "zm_" & i
next
Try the below code and hope it helps you:
For i = 1 To 100
ThisWorkbook.Sheets(1).Range("A" & i).Name = "zm_" & i
Next
Where Sheet(1) refers to Sheet1 of the current workbook.
Related
i am using an excel formula to reference, and adjust when necessary, a very long list of scraped values. my problem is that occasionally the values start with "=+" causing them to be seen as a formula, and thus producing a #NAME? error. whenever my formula references these cells, it too produces said error.
is there anyway to account for #NAME errors within my formula? something like ISNA but for #NAME errors?
if that is not possible, could i use VBA to delete "=+" from any cells that contain it?
any help would be greatly appreciated, ive been looking for an answer to this for hours.
The easiest way is to add a ' in front of each cell's formula.
Imagining you have your scraped values in the range C1:C10, you can fix it like this:
For j = 1 To 10
Range("C" & j).Value = "'" & Range("C" & j).Formula
Next j
By doing so, you preserve the original value of your scraped object.
Of course you can fix the issue at the source, i.e. imagining you print your values like this:
rng.Value = myScrapedValue
... you can replace it like this:
rng.Value = quoteFirst(myScrapedValue)
... where
Private Function quoteFirst(ByVal strng As String) As String
quoteFirst = "'" & strng
End Function
I think you could use an =IFERROR() in your formulas directly, that would save time of developping a VBA code dedicated to this specific error.
Can you not use something like...
=ERROR.TYPE(A1) =5
This should produce a TRUE-FALSE in the formula....
If you want to delete the "=+" you can use something like this :
Dim index As Integer
For index = 1 To 10
If (Mid(Cells(index, 1), 1, 2) = "=+") Then
Cells(index, 1) = Mid(Cells(index, 1), 3)
End If
Next
It will replace the content of the cells beginning by "+=" by the same content without "+=".
Is it possible to write a formula in VBA for excel such that there are "n" terms in the formula, with the number of terms changing as the value of "n" does?
For instance, say you wanted to code cell a1 such that it was the sum of a2 and a3. Then you wanted b1 to be the sum of b2,b3,b4,b5 and so on such that each column 1 row 1 cell for a range of cells is the sum of "n" cells below it where "n" varies from column to column. Say that all cell addresses you wanted to use are known and stored in an array.
Here is some code to better explain what I'm asking:
For i = 0 to n
Range(arr1(i)).formula = "=" & range(arr2(i)).value & "-(" _
& Range(arrk(i)).value & "+" & Range(arrk+1(i)).value & "+" _
& Range(arrk+2(i)).value & "+" & ... & ")"
Next i
So what I'm looking for is one piece of VBA code that can make a cell formula contain a dynamic number of terms. The code above would make cell a1's value = a-(b+c+d+...) where the number of terms in the bracket is variable, depending on which cell the formula is applied to.
The image here shows an example of what I want to do. I'd like some code which could take "years income" and subtract a variable amount of "expenses" from it, where the number of expenses varies each year (but the number stays fixed for that year). The code needs to use a formula so that the expenses entries can be modified by the user.
Have you tried Array Formula ? :
Array Formula :
An Excel Array Formula performs multiple calculations on one or more sets of values (the 'array arguments') and returns one or more results.
details : http://www.excelfunctions.net/Excel-Array-Formulas.html
Thanks for the suggestions everyone, I found a solution (not a particularly efficient one, but a solution nonetheless) to the conundrum today.
First I created an array which used the "pattern" of the Junk cells to list every cell address which was to be included.
Taking this array, I used a for loop to create a series of temporary arrays with the application.index command. For each temporary array, I used the Join command to turn the list of cells into a single string which I then inputted into a cell formula. Thanks to #thepiyush13 whose array.formula approach inspired this.
Here's some example code to show what I did:
' hypothetical array containing two sets of cells to use
Dim array1(0 To 1, 0 To 1) As Variant
Dim vartemp As Variant
Dim vartemptransposed As Variant
' col 1 will be used to add I10 and I13, col2 I11 and I14
array1(0, 0) = "$I$10"
array1(1, 0) = "$I$13"
array1(0, 1) = "$I$11"
array1(1, 1) = "$I$14"
For i = 1 to 2
'application.index(arr,row#,col#) to create a new array
vartemp = Application.Index(array1, 0, i)
'error if not transposed
vartemptransposed = Application.Transpose(vartemp)
randomstring = Join(vartemptransposed, ",")
totalvalue = 100
'example formula: a1 = totalvalue - sum(I10,I13). a2 = totalvalue - sum(I11,I14)
Cells(1,i).formula = "=" & totalvalue & "-SUM(" & randomstring & ")"
Next i
I needed the code to run this many many times on large lists which are generated dynamically but always hold the same pattern of where the "junk cells" are. Not included in the code, but I also used another array for the cell addresses of where to place the formula.
The spreadsheet has multiple values in a cell.
What I'm trying to do is get that value found in a cell and paste it to another sheet and copy the other fields(columns) that belong to that value. How do I set the range in order copy the other fields(columns) up to the last column that has value? Thanks in advance.
For iRowGetProdCode = 0 To UBound(sSplitProdCode)
Sheets("Output").Cells(iRowCountOutput, 1).Value = sSplitProdCode(iRowGetProdCode)
iRowCountOutput = iRowCountOutput + 1
Next iRowGetProdCode
here is an idea how to discover an un-empty columns in the same row,
maybe you will find it useful and manipulate it for your needs:
Function LoopUntilLastColumn(ByVal Row As Integer)
Dim i As Integer
i = 1
Do While Cells(Row, i) <> ""
' do somthing
MsgBox (" I AM ALIVE COLUMN!")
i = i + 1
Loop
' you can also use the return value of the function.
LoopUntilLastColumn = i
End Function
I'm not exactly sure about what you're asking, but here are my three best guesses.
1.) Splitting delimited data from a single cell to columns
Without VBA: Use the "Text to Columns" function (Excel Ribbon:
Data|Data Tools).
With VBA: Use the split function MSDN (Related Post), then assign array values to target cells. Or parse your string manually with a loop.
2.) Finding the end of a continuous range
Without VBA: Use ctrl + arrow key
With VBA: Use the Range.End Property
3.) Looping through columns and rows
Used a nested loop:
For c = 1 to 5
For r = 1 to 20
Cells(r,c) = "Row = " & r & ", Column = " & C
Next
Next
Editing Suggestions (I don't have enough reputation to directly comment or edit)
This question as worded may be too specific for StackOverflow. Consider re-wording so that the problem can be understood in a general context and your question can be more useful to others.
Also, the wording is a little confusing. For example, use of the term "value" seems to change from referring to delimited data to referring to cell content in VBA. Likewise, it can be confusing to use "fields" or "columns" to describe the data if it's actually delimited text, so clarity on the data's state of existence would help.
It also seems to me that you've parsed the string on it's delimiter to an array, and that you're looping through this array to write the data in rows. I still can't see how exactly your question about setting a range fits in.
I'm trying to do "vlookup" with 2 different criteria(Column A and G values) using "Index" and "Match" functions.
and here is the line i used for the Excel command.
=INDEX(Database!A:KG,MATCH(1,(Database!A:A='TempSheet'!A2)*(Database!G:G='TempSheet'!G2),0),10)
How would I do it with VBA? It's keep giving me the error message "Compile error: Expected end of statement".
Selection= _
"=Index(DB.Range("A:KG"), Match(1, (DB.Range("A" = Temp.Range("A" & i).Value)) * (DB.Range("G" = Temp.Range("G" & i).Value)), 0), 10)"
Thanks
Every time you use a spreadsheet formula inside a VBA code, you need to precede it with <Excel.WorksheetFunction.> or <Application.WorksheetFunction.>.
For example:
Application.WorksheetFunction.Match
instead of Match only.
I have had little luck getting array formulas to work correctly via VBA, and use the 'IFERROR' as a workaround like so:
=IFERROR(VLOOKUP(A1, Database!A:Z,1,FALSE),VLOOKUP(B1, Database!A:Z,1,FALSE))
This function will attempt to match A1, and in case of a #VALUE error, it will match B1.
To get this kind of formula populated on a sheet in VBA, you can loop down your sheet using the '.formula' approach.
' get length of source data
Dim RowCount As Long
RowCount = ThisWorkbook.Sheets("Database").Cells(Rows.Count, 1).End(xlUp).Row
' now starting from row 2 to preserve headings
For i = 2 To RowCount
ThisWorkbook.Sheets("Summary").Cells(i, 1).Formula = "=IF(ISERROR(SEARCH(""ISO"",V" & i & ")),""Order type not supported"",""Transit"")"
ThisWorkbook.Sheets("Summary").Cells(i, 6).Formula = "=IFERROR(TEXT(VLOOKUP(B" & i & ",Database!A:N,7,FALSE),""dd-mmm-yyyy HH:MM AM/PM""),"""")"
Next
Not exactly what you were after, but hope it helps!
I'm trying to have a formula display the number or occurrences of the previous row of column "C" (RC3).
An ideal result would look like:
Count: 3
If there were 3 occurrences of the value in the previous row.
The following code returns "False".
y.FormulaR1C1 = "Count: " + "=Application.WorksheetFunction.CountIf(range(R3C3:R" & LR & "C3), " = "&R[-1]C3)"
y is a cell
LR is the last row
Thanks, and let me know if I can clarify further.
The CountIf Function is never going to count anything as long as it's inside a test string. And you don't need 'Application.WorksheetFunction' in a cell formula (only if you want to use that function entirely in VBA). Also you don't need a range function in an Excel formula. Try this:
y.FormulaR1C1 = "=""Count: ""&CountIf(R3C3:R" & LR & "C3,R[-1]C3)"
Though if there is nothing between your search range and your criteria cell, you could eliminate LR altogether with:
y.FormulaR1C1 = "=""Count: ""&CountIf(R3C3:R[-2]C3,R[-1]C3)"
If you are trying to make a formula that combines TEXT and builtin functions, use =CONCATENATE(). consider the example below:
If you are to use VBA to fill in formula with relative location (.FormulaR1C1), it would be:
=CONCATENATE("Count: ",COUNTIF(R[-5]C:R[-2]C,"=" &R[-1]C))