写一个VBA代码,要求如下:将一个Excel表格上的数据拆分到其他两个Excel表中
时间: 2023-11-22 12:53:59 浏览: 264
以下是一个示例VBA代码,可以将Excel表格中的数据拆分到两个新的Excel表中。在这个示例中,我们将假设原始表格的名称为“Sheet1”,第一个新表格的名称为“NewSheet1”,第二个新表格的名称为“NewSheet2”。
```VBA
Sub SplitData()
Dim srcSheet As Worksheet
Dim newSheet1 As Worksheet
Dim newSheet2 As Worksheet
Set srcSheet = ThisWorkbook.Worksheets("Sheet1")
Set newSheet1 = ThisWorkbook.Worksheets.Add(After:=srcSheet)
newSheet1.Name = "NewSheet1"
Set newSheet2 = ThisWorkbook.Worksheets.Add(After:=newSheet1)
newSheet2.Name = "NewSheet2"
Dim srcData() As Variant
srcData = srcSheet.UsedRange.Value
Dim newData1() As Variant
ReDim newData1(1 To UBound(srcData), 1 To 3)
Dim newData2() As Variant
ReDim newData2(1 To UBound(srcData), 1 To 3)
Dim i As Long
Dim j As Long
Dim k As Long
For i = 1 To UBound(srcData)
If srcData(i, 1) = "A" Then
k = k + 1
For j = 1 To 3
newData1(k, j) = srcData(i, j)
Next j
Else
k = k + 1
For j = 1 To 3
newData2(k, j) = srcData(i, j)
Next j
End If
Next i
newSheet1.Range("A1:C" & k).Value = newData1
newSheet2.Range("A1:C" & k).Value = newData2
End Sub
```
这段代码将会把“Sheet1”中的数据根据第一列的值拆分到两个新的表格中。如果第一列的值是“A”,则数据将被复制到“NewSheet1”中;否则,数据将被复制到“NewSheet2”中。在新的表格中,数据将被复制到A、B、C列中,分别对应原始表格中的A、B、C列。
阅读全文