gpt4 book ai didi

excel - 将可变数量的值复制到另一个电子表格

转载 作者:行者123 更新时间:2023-12-02 19:26:14 28 4
gpt4 key购买 nike

我正在尝试获取一个范围(假设为 C:C),遍历所有具有值的单元格并将它们粘贴到另一个电子表格中。

我的目标是将可变数量的值(因为我不知道 C:C 中有多少个值)复制到另一张工作表,因此我有一个包含所有值的新范围(其中没有重复值)。

如何编写 If 语句(对于可变数量的值)?

Sub Test_1()
' Go through each cells in the range
Dim rg As Range
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet

Set copySheet = Worksheets("Data")
Set pasteSheet = Worksheets("Data_storage")

For Each rg In Worksheets("Data").Range("C:C")

If rg.Value = "Client 1" Then 'Instead of "Client 1" should be a variable value because "Client 1" will be a repetead value in C:C
copySheet.Range("C2").Copy 'Starting the counter in C2
pasteSheet.cells(Row.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValue
End If

Next

End Sub

最佳答案

假设您在“数据”工作表中的值:

  • 位于“C”列

  • 从第 1 行开始,带有“标题”

那么你可以试试这个代码:

Option Explicit

Sub Test_1()
Dim sourceRng As Range, pasteRng As Range, cell As Range

Set pasteRng = Worksheets("Data_storage").Range("A1") '<--| set the upper-left cell in "paste" sheet

With Worksheets("Data") '<--| reference "source" sheet
Set sourceRng = .Range("D1", .Cells(.Rows.Count, "C").End(xlUp)) '<--| set the "source" range to columns "C:D" from row 1 down to last non empty cell in column "C"
End With

With sourceRng '<--| reference "source" range
.Sort key1:=.Range("a1"), order1:=xlAscending, key2:=.Range("B1"), order2:=xlAscending, header:=xlYes '<--| sort it by its column 1 and then by its column 2
pasteRng.Resize(.Rows.Count).value = .Resize(, 1).value '<--| paste its column 1 values to "Paste" sheet column 1
pasteRng.CurrentRegion.RemoveDuplicates Columns:=Array(1) '<--| leave only unique values in "paste" range
Set pasteRng = pasteRng.Range(pasteRng.Offset(1), pasteRng.End(xlDown)) '<--| skip "paste" range header
For Each cell In pasteRng '<--| loop through unique values in "paste" range column 1
.AutoFilter field:=1, Criteria1:=cell.value '<--| filter "source" range column 1 with current unique value
.Offset(1, 1).Resize(.Rows.Count - 1, 1).SpecialCells(xlCellTypeVisible).Copy '<--| copy "source" range" column 2 filtered cells
cell.Offset(, 1).PasteSpecial Transpose:=True '<--| ... and paste/transpose them aside current unique value in "paste" range
Next cell
.Parent.AutoFilterMode = False '<--| .. show all rows back...
End With
End Sub

关于excel - 将可变数量的值复制到另一个电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39187725/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com