1. Flatten and fill the data in range A to range B
1. Description of requirements
Fill the range A7:A18 with the value of A2:D4 as follows:
2. Realize
Idea: Get the value in the range of A2:D4 to an array, loop the array, and write the value to A7:A18
- The first step is to insert a button in excel. The author uses a rectangle here. Right-click the rectangle, select "Specify Macro", enter the macro name in the pop-up box, click New, and open the VB editor
- The second step is to get the value of A2:D4
Dim arr
arr = Worksheets("sheet1").Range("A2:D4")
- The third step is to loop through arr and output each value in the immediate window (similar to the command window and console)
For Each i In arr
Debug.Print i
Next
- The fourth step, the target range is A7:A18, so define a start equal to 6, when traversing arr, start will increase by 1, and assign a value to Astart:
Dim start
start = 6
For Each i In arr
start = start + 1
Worksheets("sheet1").Range("A" & start).Value = i
Next
The complete code is as follows:
Sub 矩形2_Click()
Dim start
Dim arr
start = 6
arr = Worksheets("sheet1").Range("A2:D4")
For Each i In arr
start = start + 1
Worksheets("sheet1").Range("A" & start).Value = i
Next
End Sub
- Step 5: Click the rectangle to write data into the specified range.
2. Traverse the cells and output two columns, the first column is the cell name, and the second column is the corresponding value
1. Description of requirements
Fill the data of A1:C4 to A6:B18, the first column displays the cell name, and the second column displays the corresponding value, for example, A1 corresponds to aaa:
2. Realize
Get the cell name: target.Cells.Address(0, 0)
Get value: target.Cells
Sub 矩形1_Click()
Dim start
start = 5
For Each i In Worksheets("sheet2").Range("A1:C4")
start = start + 1
Worksheets("sheet2").Range("A" & start).Value = i.Cells.Address(0, 0)
Worksheets("sheet2").Range("B" & start).Value = i.Cells
Next
End Sub
Summarize
This article records the method of using VBA to obtain data in a specified range, traverse the data, and dynamically assign values to a specified range, for personal study and reference!