VBA Copy and Paste random cells in a loop using VBA - vba

I will like to Copy and Paste cells in one worksheet with VBA, to another sheet in VBA using a loop.
For example, I will like to copy cell A2 in sheet2 to cell A1 in sheet1, cell B2 in sheet2 to cell B1 in sheet1. Then A3 in sheet2 to cell A1 in sheet1, cell B3 to cell B1 in sheet1. I will like to do this until the last row.
I tried the code below, but my data set is too large. Is there another alternative method?
'Worksheets("Sheet1").Range("C28").Value = Worksheets("Sheet2").Range("B2").Value

hi when im doing things like this i find it easiest to record a macro, then if you go to view your macros and edit them you can see the code that was created. that can be copied straight in to your vba project

OK, I think you might want something along these lines.
Sub x()
Dim r As Long
With Sheet2
For r = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
Sheet1.Range("A1").Resize(, 2).Value = .Cells(r, 1).Resize(, 2).Value
'presumably do something else?
Next r
End With
End Sub

Hi you can use Random number to generate row and column number
Sub test1()
Dim LastRow, Lastcol As Long
Dim wb As Workbook
Dim ws1, ws2 As Worksheets
Set wb = ThisWorkbook
' Sheet name where data is present
Set ws1 = wb.Worksheets("OriginalSheet")
' Sheet name where data to be copied
Set ws2 = wb.Worksheets("CopySheet")
With ws1
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
Lastcol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
For i = 1 To Lastcol
For j = 1 To LastRow
' Random number generation
' To create a random integer number between two values (range), you can use the following formula:
' Int ((upperbound - lowerbound + 1) * Rnd + lowerbound)
randrow = Int((50 - 10 + 1) * Rnd + 10)
randcol = Int((5 - 2 + 1) * Rnd + 2)
ws2.Cells(randrow, randcol).Value = ws1.Cells(j, i).Value
Next
Next
End Sub

Related

need vba macro to delete cells except first and last row in each column

I have a excel which has multiple rows and columns and range of column values differ for each row.
Need a macro which will delete all cells in a row except first and last in each row and paste the last value next to first value.
Tried the below script:
Sub test()
Dim sh As Worksheet
Dim IDS As range
Dim ID As range
Set sh = ThisWorkbook.Sheets("Sheet1")
Set IDS = ActiveSheet.range("A2", range("A1").End(xlDown))
For Each ID In IDS
Dim b As Integer
Dim k As Integer
k = sh.range("ID", sh.range("ID").End(xlToRight)).Columns.Count
b = k - 1
range(ID.Offset(0, 0), ID.Offset(0, "b")).Select
Selection.ClearContents
Next ID
End Sub
This is a little different approach but should help.
Also, it is generally not best to declare variables in a loop as you do with b & k just fyi
Sub test()
Dim sh As Worksheet
Dim row As Integer
Dim lastCol As Integer
Set sh = ThisWorkbook.Sheets("Sheet1")
For row = 2 To sh.Cells(Sheets(1).Rows.Count, "A").End(xlUp).row
lastCol = sh.Cells(row, Columns.Count).End(xlToLeft).Column
sh.Range("B" & row).Value = sh.Cells(row, lastCol).Value
sh.Range(sh.Cells(row, 3), sh.Cells(row, lastCol)).ClearContents
Next
End Sub
Best of luck
I'd go as follows:
Sub test()
Dim cell As Range
With ThisWorkbook.Sheets("Sheet1") ' reference relevant sheet
For Each cell In .Range("A2", .Cells(.Rows.Count, "A").End(xlUp)) ' loop through referenced sheet column A cells from row 2 down to last not empty one
With .Range(cell, .Cells(cell.Row, .Columns.Count).End(xlToLeft)) ' reference referenced sheet range spanning from current cell to last not empty one in the same row
If .Count > 2 Then ' if referenced range has more then 2 cells
cell.Offset(, 1).Value = .Cells(1, .Count).Value ' store last cell value next to the current one
.Offset(, 2).Resize(, .Columns.Count - 1).ClearContents 'clear all cells right of current one
End If
End With
Next
End With
End Sub
You can use Range.Delete Method (Excel)
range(ID.Offset(0, 0), ID.Offset(0, b)).Delete Shift:=xlToLeft

loop through adding values in a range (5x5 for example) of row and columns in multiple sheets and dump in one particular sheet

I have multiple sheets in a single workbook with values in 5 rows and 5 columns in each sheet. I need to add the corresponding cell values (eg: D5) in each sheet and dump it in a new sheet in its D5. I could do it for one particular cell, but I'm confused on how to do it in nested for loops. I've only been doing vba for a day.. so please help. Thanks.
Sub Macro1()
Dim i, val
'Select worksheets
For i = 7 To Sheets.Count
val = val + Sheets(i).Range("e6")
Next
Sheets("Summation").Range("e6") = val
End Sub
Is this what you want?
Sub Sample()
Dim ws As Worksheet, wsSumry As Worksheet
Dim startRow As Long, StartCol As Long
Dim i As Long, j As Long
Dim ar(1 To 4, 1 To 4) As Variant
'~~> Start row and start column
startRow = 2: StartCol = 2
'~~> Summary sheet
Set wsSumry = Sheet1
'~~> Looping through each worksheet
For Each ws In ThisWorkbook.Worksheets
'~~> Check if it is not the summary sheet
If ws.Name <> wsSumry.Name Then
'~~> Loop through the row and columns and
'~~> Store it in an array
For i = startRow To (startRow + 3)
For j = StartCol To (StartCol + 3)
ar(i - 1, j - 1) = ar(i - 1, j - 1) + ws.Cells(i, j)
Next j
Next i
End If
Next
'~~> Write array to summary sheet
wsSumry.Range("B2").Resize(UBound(ar), UBound(ar)).Value = ar
End Sub
Screenshot
You can use Copy and Add technique, cycling through each sheet that isn't the summisary sheet and then pasting its values in to the final sheet (while adding them) - something like:
Dim b As Worksheet
Set b = ThisWorkbook.Worksheets("Sheet4")
b.range("A1:A2").clear
For Each a In ThisWorkbook.Sheets
If Not a.Name = b.Name Then
a.Range("A1:A2").Copy
b.Range("A1:A2").PasteSpecial operation:=xlAdd
End If
Next
Obviously your range can be defined in place of "A1:A2"
I'm sure there's a more "code" way of adding arrays together but in Excel this might prove good for you.

VBA Copy column and paste formulas only - not values - to next column

VBA Copy column and paste formulas only - not values - to next column
Spreadsheet column B has a random mix of values and formulas. I want to use VBA to copy that column into the next column and only copy the formulas (not the values) into column C. I was able to use the following VBA to some success but it copies every column past B to infinity (where I want it to stop copying after the first column).
Sub Copy_Column_Formulas_NOvalues()
'
' Copy_Column_Formulas_NOvalues Macro
'
Dim oSheet As Worksheet
Dim rng As Range
Dim cel As Range
Set oSheet = Sheets("Sheet1")
With oSheet
Set rng = .Range(.Range("B1"), .Range("B" & .Rows.Count).End(xlUp))
For Each cel In rng
If Left(cel.Formula, 1) = "=" Then
Range(cel.Offset(, 1), cel.Offset(, 1).End(xlToRight)).FormulaR1C1 = cel.FormulaR1C1
End If
Next cel
End With
End Sub
Try this simple macro and let me know if it works,
Sub Copy_Column_Formulas_NOvalues()
Dim i As Long, j As Long
For i = 1 To Sheets("Sheet3").Cells(Rows.Count, "B").End(xlUp).Row
If Cells(i, 2).HasFormula Then
Cells(i, 3) = Cells(i, 2).Formula
End If
Next i
End Sub
Change the Sheet3 name as per your needs.

Excel Moving Data From Rows Into a Column

Sorry, I feel like this is probably super basic, but I am trying to use Excel and VBA to move data from multiple cells per row into an empty column in a specific order. Some of the cells might not have data so I have to check that as well and skip empty ones with something along the lines of Value <> Empty.
Basically, what I am trying to do is take a table that looks like this (with empty column A):
B1 C1 D1 E1
B2 C2 D2 [E2empty]
B3 C3 D3 E3
And set it up like this in column A:
B1
C1
D1
E1
B2
C2
D2
B3
C3
D3
E3
It would be entered in one row at a time into the new column.
I guess I am trying to figure out how to say the following in code
In Row 1, check if cell B is empty. If not, move Value to column A, first avaible cell,
next cell in row 1, (repeat).
Next Row( do the same as row 1.)
So I was thinking of using For i = 1 To rwcnt where rwcnt is defined by CountA(Range("B:B"))
To do the rows in order and then doing a similar thing inside that for-statement for cells (Maybe j = B To E?).
So my overall goal is to scan my range (MyRange = ActiveSheet.Range("B1:E" & rwcnt)) and move everything into column A in the order described at the top, but I don't know how to move data to column A in sequence. Any advice on how to accomplish this would be very helpful.
Loop through all the used rows, looping columns starting at B in that row. Check if the cell is not empty. Write it to A next cell.
In you VBA IDE go to the tools menu and selecte references. Select "Microsoft scripting runtime"
Dim lRow As Long
Dim lRowWrite as long
Dim lCol As Long
Dim ws As Excel.Worksheet
Dim ts As TextStream
Dim fs As FileSystemObject
'Create the text file to write to
Set fs = New FileSystemObject
Set ts = fs.CreateTextFile("C:\Temp\test.txt", True, False)
Application.ScreenUpdating = False
Set ws = Application.ActiveSheet
lRowWrite = 1
lRow = 1
'Loop through all the rows.
Do While lRow <=ws.UsedRange.Rows.count
'Loop through all the columns
lCol = 2
Do While lCol <=ws.UsedRange.Columns.count
'Check if it is empty
If not isempty(ws.Cells(lRow, lCol)) Then
'Not empty so write it to the text file
ts.WriteLine ws.Cells(lRow, lCol)
End If
lCol = lCol + 1
Loop
lRow = lRow + 1
ws.Range("A" & lRow).Activate
Loop
Application.ScreenUpdating = True
ts.Close: Set ts = Nothing
Set fs = Nothing
Try this:
Sub test()
Dim lastCol As Long, lastRow As Long, k As Long, i As Long, colALastRow As Long
Dim rng As Range
Dim ws As Worksheet
'Columns(1).Clear ' uncomment this if you want VB to force Col. A to be cleared
Application.ScreenUpdating = False
Set ws = ActiveSheet
lastCol = ws.UsedRange.Columns.Count 'This will get the last column
lastRow = ws.UsedRange.Rows.Count 'this will get the last used row
k = 2 'Set k to 2, to start in Col B
colALastRow = 1 'This starts at 1, since your entire Column A is empty
With ws
For i = 1 To lastRow
lastCol = .Cells(i, 2).End(xlToRight).Column
Set rng = .Range(.Cells(i, 2), .Cells(i, lastCol))
' rng.Select
rng.Copy
.Range(.Cells(colALastRow, 1), .Cells(colALastRow + (lastCol), 1)).PasteSpecial Paste:=xlPasteAll, operation:=xlNone, skipblanks:=False, Transpose:=True
Application.CutCopyMode = False
colALastRow = .Cells(1, 1).End(xlDown).Row + 1
Next i
End With
Application.ScreenUpdating = True
MsgBox ("Done!")
End Sub
Edit: Changed the lastCol, lastRow, etc. from Integer to Long, since there will be over 32,767 rows.
Edit 2: I commented out rng.Select. This is because there's no reason to select it for the Macro. I only had it there, because as I worked through the macro (using F8), I wanted to make sure it was grabbing the right ranges. It is, so you can comment this out. It might even make it run slightly faster :)

How to multiply cells in one excel sheet with multiple cells in another excel sheet

I have a workbook with two excel sheets: sheet1 and sheet2. In sheet1 I have a large amount of data from column B to CE.
Using VBA I am currently copying each row from Sheet1 in the range "B3:AP3" to Sheet2 duplicating each line so it will be represented twice. This is working fine!
The problem i have as that in Sheet2 I now need to make a calculation. In Sheet1 I have a number in cell CE and CF for each row. As these rows have been duplicated I need to multiply the number in cell AP3 of Sheet2 with that of CE3 in Sheet1 and that of AP4 in Sheet2 with that of CF3 in Sheet1.
The macro needs to keep on doing this with the subsequent cells. In total cell AP the first duplicated line needs to be multiplied with the number CE3 from Sheet1 and cell AP of the second duplicated line needs to be multiplied with the number CF3 from sheet1. The result should be posted in Sheet2 column AQ.
Below I have posted the code for duplicating and moving the lines but I am really struggling with the multiplications, any help is greatly appreciated!
Sub CopyRows()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim i As Long, k As Long
Dim ws1LR As Long, ws2LR As Long
Set ws1 = Sheets("Bearbejdning")
Set ws2 = Sheets("Sheet8")
ws1LR = ws1.Range("B" & Rows.Count).End(xlUp).Row + 1
ws2LR = ws2.Range("B" & Rows.Count).End(xlUp).Row + 1
i = 2
k = ws2LR
Do Until i = ws1LR
With ws1
.Range(.Cells(i, 1), .Cells(i, 43)).Copy
End With
With ws2
.Cells(k, 1).PasteSpecial
.Cells(k, 1).Offset(1, 0).PasteSpecial
End With
Range("k,AR" & ws2LR).Formula = "=ws1.range(.Cells(i, 73)) * ws2.range(.Cells(k, 36))"
k = k + 2
i = i + 1
Loop
End Sub
You can't pass an object into an excel formula that way.
Try this:
Range(k,"AR" & ws2LR).Formula = "=" & ws1.range(.Cells(i, 73)).address &" * " & ws2.range(.Cells(k, 36)).address
Alternatively, you could place the pre-calculated value in the cell.
Range(k,"AR" & ws2LR).Value = ws1.range(.Cells(i, 73)) * ws2.range(.Cells(k, 36))
Also, this Range call looks strange to me: Range("k,AR").
I think it should be something like Cells(k,"AR").
Variables shouldn't be inside quotes and Range doesn't accept Row/Column parameters.