filmov
tv
Use a For Loop and If Statement to loop through an Array and add data to another Sheet in VBA Code
![preview_player](https://i.ytimg.com/vi/hBqbKIDr37A/maxresdefault.jpg)
Показать описание
Grab the Free VBA Quick Reference Guide
Master this process and you will will quickly become an Excel VBA Master.
Move data from one sheet to another using
CurrentRegion
Arrays
For Next Loops
Ubound
If Statement using criteria from an Input Box
And clearing a reporting sheet using a CurrentRegion.Offset(1,0).clear
This solution moves data from a master data set in Sheet1 to Sheet2.
We use CurrentRegion to take data from sheet one and put it into an array we then loop through that array with a for next loop using the Ubound of the array. Then to make it more fun we add an If statement to find specific rows that we want to move to Sheet2 based data from an input box. To do this we use another for loop and Ubound of the second index of the array (number of columns in the array). We delete the data at the beginning of the code and ad a button.
Code:
Sub LoopArray()
ibox = InputBox("Enter MPG over X", "MPG")
oarray = Sheet1.Cells(1, 1).CurrentRegion
rprw = 2
For rw = 2 To UBound(oarray)
If oarray(rw, 1) "GT" ibox Then
'Stop
For cl = 1 To UBound(oarray, 2)
Sheet2.Cells(rprw, cl) = oarray(rw, cl)
Next
rprw = rprw + 1
End If
Next
End Sub
Master this process and you will will quickly become an Excel VBA Master.
Move data from one sheet to another using
CurrentRegion
Arrays
For Next Loops
Ubound
If Statement using criteria from an Input Box
And clearing a reporting sheet using a CurrentRegion.Offset(1,0).clear
This solution moves data from a master data set in Sheet1 to Sheet2.
We use CurrentRegion to take data from sheet one and put it into an array we then loop through that array with a for next loop using the Ubound of the array. Then to make it more fun we add an If statement to find specific rows that we want to move to Sheet2 based data from an input box. To do this we use another for loop and Ubound of the second index of the array (number of columns in the array). We delete the data at the beginning of the code and ad a button.
Code:
Sub LoopArray()
ibox = InputBox("Enter MPG over X", "MPG")
oarray = Sheet1.Cells(1, 1).CurrentRegion
rprw = 2
For rw = 2 To UBound(oarray)
If oarray(rw, 1) "GT" ibox Then
'Stop
For cl = 1 To UBound(oarray, 2)
Sheet2.Cells(rprw, cl) = oarray(rw, cl)
Next
rprw = rprw + 1
End If
Next
End Sub
Комментарии