gpt4 book ai didi

excel - 如何在列为空时将值粘贴到列中,当列不为空时将列中的值粘贴到右侧?

转载 作者:行者123 更新时间:2023-12-04 20:48:48 26 4
gpt4 key购买 nike

我目前正在研究 Excel VBA。
我有 2 个标签。第一个选项卡名称是“数据”(数据从服务器中提取),第二个选项卡名称是“月份”。
我想将“数据”选项卡中的列条目复制到“月份”选项卡中的特定列。但是当新的月份数据到来时,我想做同样的方法,但每次不为空时将复制范围偏移 1。
下面的例子。

Data Tab

Column A
45
65
78
99

The above 4 rows of data for Column A change each month.
下面是要粘贴的月份标签。
    A              B             C             D             E            F         G
2022/01/31 | 2022/02/28 | 2022/03/31 | 2022/04/30 | 2022/05/31 | Total YTD |
26 | | | | | 26 |
74 | | | | | 74 |
87 | | | | | 87 |
98 | | | | | 98 |
我想将“数据”选项卡编号中的 A 列粘贴到“月份”选项卡中的 B 列,但代码应以 A 列开头,如果 A 列为空,则粘贴数据,否则移动到 B 列,如果 B 列为空,则粘贴数据.如果 B 列不为空,则移至 C 列,依此类推。
到目前为止,这是我的代码,但它仅将数据粘贴到 G 列中。任何建议或帮助将不胜感激。
 Sub Copy_total()
'
' Copy_total Macro
'
' Keyboard Shortcut: Ctrl+q
'
Application.ScreenUpdating = False
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet

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

copySheet.Range("A2:A5").Copy
If pasteSheet.Cells(2, 1) = "" Then
pasteSheet.Cells(2, 1).PasteSpecial xlPasteValues
Else
pasteSheet.Cells(2, Columns.Count).End(xlToLeft).Offset(0, 1).PasteSpecial
xlPasteValues
End If

Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub

最佳答案

尝试类似:

 Sub Copy_total()
'
' Copy_total Macro
'
' Keyboard Shortcut: Ctrl+q
'
Application.ScreenUpdating = False
Dim sourceSheet As Worksheet
Dim destSheet As Worksheet
Dim destCells

Set sourceSheet = Worksheets("Data")
Set destSheet = Worksheets("Months")

sourceSheet.Range("A2:A5").Copy
Set destCells = destSheet.Cells(2, 1)

' Skips cells already filled.
Do While destCells <> ""
Set destCells = destCells.Offset(0, 1)
Loop

destCells.PasteSpecial xlPasteValues

Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub

关于excel - 如何在列为空时将值粘贴到列中,当列不为空时将列中的值粘贴到右侧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70884026/

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