reading clipboard contents into array in VBA - excel

Range("C" & CStr(j) & ":C" & CStr(k)).Select
Range("C" & CStr(j) & ":C" & CStr(k)).Copy
I am reading the contents of a column into the clipboard and I want to loop through every element.
The question is how do I loop through it?
The contents of the clipboard look like this:
1234
21345234
1234512345
123452135
123451235
2345
alternatively I should probably be looping through J and K? Can you please show me how to do this thank you

You don't need to use the clipboard for this, instead:
Dim workingArray as Variant
workingArray = Range ("C" & CStr(j) & ":C" & CStr(k))
Now you can work through workingArray, note that it's treated as a two-D array.

You can loop through the range without the need for any weird syntax like this:
Dim cel as Range
For Each cel in Range(Cells(j,3), Cells(k,3))
MsgBox cel.Value
Next cel
Note that the '3' in this case means the range is in the third column (which is 'C')

Related

Can you explain how this line of code work (worksheet function)

Hello I'm new to vba and I have a project which at first seems quite simple but when I started to look at the range references I was totally lost. The Goal is to make a sum of multiple columns with one or two criterias.
For j = 9 To 12
For i = 3 To 6
datecol = 3
Cells(i, j).FormulaR1C1 = "=SUMIFS(R3C" & datecol & ":R" & Lastrow2 & "c" & datecol & ", R3C2:R" &
Lastrow2 & "C2, R" & i & "C8"
Next i
datecol = datecol + 1
Next j
End sub
What I have understand is that Cells(i,j) is where the output of my formula will be write.
.FormulaR1C1 return the formula as a string in the cell (i,j) -I think this is why we have ="=sumifs()-
Then we have SUMIFS(R3C" & datecol & ":R" & Lastrow2 & "c" & datecol & ") but what ":R", "c", & " mean ?
I know that this argument is the range use by the formula to make the sum but I don't understand the way ranges are referenced, and I have the same question for R3C2:R" "C2, R".
Help would be very appreciated, thank you.
Review and Suggestions
What do :R, c, & mean ?
In the context of R1C1 style R means row and C column. The & is a concatenation operator used to join the values ​​of two variables or constants. Very common used to create String variables.
For the macro you are trying to code you don't need to complicate yourself with .FormulaR1C1 use .Formula instead.
The line datecol = datecol + 1 is useless because datecol = 3 is inside the loop, so datecol will go back to 3 everytime the macro is looping. To solve this, datecol = 3 should be outside the loop.
When working with VBA is better to use functions that are meant to be runned in VBA and not in Excel, unless you wish to insert Excel formulas in cells. For instance the SUMIF function in VBA is: application.worksheetfunction.sumif(range,criteria,sum_range) Example of use: SumIfResult = Application.WorksheetFunction.SumIf(Range("A1:A10"), "In", Range("B1:B10"))
Descriptive Variables: use name or letters for your variables that describe them. It is easy to write software that works satisfactory. But it is very hard to write reliable, understandable and maintainable code. One important aspect is using good variable and function names. For instance, in the code below I changed the variables i and j for col and row_number.
I don't really get what you are trying to do, but I modified a little bit your code so you can maybe take some useful ideas.
Sub sum_columns()
'descriptive variable examples
Dim col As Long
Dim row_number As Long
Dim date_col As Long
Dim last_row2 As Long
date_col = 3
For col = 9 To 12
For row_number = 3 To 6
'this looks very complicated try to code it as simple as possible
'Cells(i, j).FormulaR1C1 = "=SUMIFS(R3C" & datecol & ":R" & Lastrow2 & "c" & datecol & ", R3C2:R" & Lastrow2 & "C2, R" & i & "C8"
'example
Cells(row_number, col).Formula = "=SUMIF(D" & row & ":D" & row + 3,">100)"
'another idea
Cells(row_number, col) = _
Application.WorksheetFunction.SumIf(Range("A1:A10"), "In", Range("B1:B10"))
Next row_number
date_col = date_col + 1
Next col
End Sub
Note
The code above is ONLY meant for explanation purposes (concepts, examples and ideas) NOT for executing it.

How to insert, through VBA, a formula in a cell with special characters like "-" or "$"?

I searched on internet, without any help coming out of that...
I simply would like to be able to have my VBA code to write this formula in a cell :
=IF(C4="-"; "-"; Cars!C4*C4*Data!$C$8)
As you guessed, there is a page called "Cars" and one called "Data" where I pick the informations needed.
Of course, as it is a VBA code, the C4 will be 2 variables, one for the C and one for the 4 that will evolve...
Actually, I tried this :
Worksheets("Calculation").Range(Column & PosStartCalc + 1).Formula = "=" & "IF(" & Column & PosStartCalc & " = " & "" - "" & ";" & " - " & ";" & "Cars!" & Column & PosStart & "*" & Column & PosStartCalc & "*" & "Data!" & "C" & "8" & ")"
(The variable Column contains the column letter and the variable PosStartCalc contains the row number)
This hurts my eyes and apparently VBA's ones too as it gives the error "Run-Time error '13': Type Mismatch'
Could anyone tell me how to do that?
Thanks in advance !
Try the following, assuming the column variable is a string and row a long variable. I might not have all the variables right, but you'll be able to get what I meant to do here.
Sub test()
Dim Col As String: Col = "C"
Dim Rw As Long: Rw = 4
With ThisWorkbook.Sheets("Calculation")
Debug.Print "=IF(" & Col & Rw & "=""-"",""-"",Cars!" & Col & Rw & "*" & Col & Rw & "*Data!$C$8)"
.Cells(Rw + 1, Col).Formula = "=IF(" & Col & Rw & "=""-"",""-"",Cars!" & Col & Rw & "*" & Col & Rw & "*Data!$C$8)"
End With
End Sub
So what you might forget easily is to use the , as parameter delimiter in a VBA programmed formula. When you put this on your sheet Excel will automatically replace that with the appropriate delimiter for your region.
Another thing to keep in mind; whenever you about to use a string value in such an function, don't forget to wrap it in double quotes!
Don't forget to remove the Debug.print .... line. It was merely there to show the output :)

Excel VBA For Loop writing Formula in cells depending on the number in the loop

I am trying to write a Forumla in cells (from cell A2 to AI, where I is the number in the For Loop).
The formula to be written must correspond to Cell M2 to MI, also where I is the number in the For Loop.
I am able to write the sheet-reference by itself:
ws.Cells(1 + I, KolonneForX + 1).Formula = " ='" & ws.Name & "'"
which gives me the formula ='Ark1' (by it self) in the cells i want.
And also the right name of cell to read:
ws.Cells(1 + I, KolonneForX + 2).Formula = "=CONCATENATE(""M"",TEXT(" & I & "+1,""0""))"
which gives me the formula MI (by it self, with the corresponing number for I) in the cells i want.
But when I try to put the two of them togheter, I can't get it to run and refer to the right cells.
This is the code I have been trying to run:
Sub OppretteKnutepunkt()
Dim ws As Worksheet
Set ws = Worksheets("Ark1")
Dim KolonneForX As Integer
For I = 1 To 5
ws.Cells(1 + I, KolonneForX + 2).Formula = "='" & ws.Name & "'!CONCATENATE(""M"",TEXT(" & I & "+1,""0""))"
Next I
End Sub
I want the Cell A2 to have the following formula:
='Ark1'!M2
I want the Cell A3 to have the following formula:
='Ark1'!M3
and so on.
Any suggestions?
You can achieve this without looping
Dim I as Long
I = 7
With ws.Range("A2:A" & I)
.Formula = "='" & .Parent.Name & "'!M2"
End With
With is a shorthand way of using the same prefix on a block of code. The VBA compiler prefixes everything that begins with a . with whatever is declared by the With block
The equivalent of the above would be:
ws.Range("A2:A" & I).Formula = "='" & ws.Range("A2:A" & I).Parent.Name & "'!M2"

Worksheet Function Countifs for resizable range

I have a table in which I count the records through Worksheet.Function.Countif.
It is nice because it counts the rows using .Rows.Count and so I am alwasy ensured if my table changes the size.
It looks like that (subset of the code):
endrow = .Cells(.Rows.Count, 20).End(xlUp).Row
ws1.Cells(6, 34).Formula = "=COUNTIF(" & .Range("U6:U" & endrow).Address & ",U6)"
I wish to write the the worksheet.function formula in the same way as above but for 'Countifs'. In excel, I would type it like that:
=COUNTIFS($U$6:$U$144;U6;$T$6:$T$144$;"<>"&T6)
How to write it in vba, using 'endrow' as in the first demonstarted code, i.e. without '144' as the last row but with '& endrow' ?
I was trying multiple times, but I cannot get it to work :/
I will appreciate any help.
Try this:
ws1.Cells(6, 34).Formula = "=COUNTIFS($U$6:$U$" & endrow & ",U6,$T$6:$T$" & endrow & "," & """" & "<>" & """" & "&T6" & ")"
This formula gets the last row of column A:
=IFERROR(LOOKUP(2,1/(NOT(ISBLANK(A:A))),ROW(A:A)),0)

How to define a Range in excel say like Range("B &i : C" & j)

There is one table in my excel spreadsheet.
So I want to start the other table from a defined range below it.
Please help me to set a range like
Excel.Application.ActiveWorkbook.Sheets(1).Range("B &i : C" & j)
.Sheets(1).Range("B" & i & ":C" & j)
Anything between " will be treated as strings.
Also if you are doing this from VBA Excel then it is no point in writing Excel.Application. It is understood by default.
Also if you want the range from the workbook from where the code is run then you don't need Activeworkbook You can use ThisWorkbook Reason being It's not necessary that both will be same at all times.
Set Rng = ThisWorkbook.Sheets(1).Range("B" & i & ":C" & j)

Resources