gpt4 book ai didi

vba - 如何在同一工作表Excel VBA中复制列

转载 作者:行者123 更新时间:2023-12-03 01:47:17 25 4
gpt4 key购买 nike

我有一个程序需要复制同一工作簿和工作表中的选定列。当前代码会导致 Excel 崩溃,因此我不确定它是否有效。

是否有更好的方法来复制同一工作簿中同一工作表中的列?

代码:

Sub Macro1()

Dim wb1 As Workbook

'Set it to be the file location, name, and file extension of the Working File
Set wb1 = Workbooks.Open("Z:\XXX\Working File.xlsx")

MsgBox "Copying Fields within Working File"

wb1.Worksheets(1).Columns("G").Copy wb1.Worksheets(1).Columns("H").Value
wb1.Worksheets(1).Columns("J").Copy wb1.Worksheets(1).Columns("O").Value
wb1.Worksheets(1).Columns("K").Copy wb1.Worksheets(1).Columns("N").Value
wb1.Worksheets(1).Columns("M").Copy wb1.Worksheets(1).Columns("P").Value

wb1.Close SaveChanges:=True

End Sub

最佳答案

试试这个,它将两个范围的值设置为相等,这将保留数据,但不格式化。应该会更快。

Sub Macro1()
Dim wb1 As Workbook
'Set it to be the file location, name, and file extension of the Working File
Set wb1 = Workbooks.Open("Z:\XXX\Working File.xlsx")

MsgBox "Copying Fields within Working File"

With wb1.Worksheets(1)
.Columns("H").Value = .Columns("G").Value
.Columns("O").Value = .Columns("J").Value
.Columns("N").Value = .Columns("K").Value
.Columns("P").Value = .Columns("M").Value
End With

wb1.Close SaveChanges:=True

End Sub

请注意,您正在使用整列,因此它可能会挂起或需要更长的时间。如果需要,您可以只获取每列的最后一行并使用它来缩短复制的范围。

编辑:如上所述,您最好使用较小的范围。这有点冗长,但您应该能够理解它在做什么:

Sub Macro1()
Dim wb1 As Workbook
Dim lastRow As Long
'Set it to be the file location, name, and file extension of the Working File
Set wb1 = ActiveWorkbook

MsgBox "Copying Fields within Working File"

With wb1.Worksheets(1)
lastRow = .Cells(.Rows.Count, "G").End(xlUp).Row
.Range("H1:H" & lastRow).Value = .Range("G1:G" & lastRow).Value

lastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
.Range("O1:O" & lastRow).Value = .Range("J1:J" & lastRow).Value

lastRow = .Cells(.Rows.Count, "K").End(xlUp).Row
.Range("N1:N" & lastRow).Value = .Range("K1:K" & lastRow).Value

lastRow = .Cells(.Rows.Count, "M").End(xlUp).Row
.Range("P1:P" & lastRow).Value = .Range("M1:M" & lastRow).Value
End With

wb1.Close SaveChanges:=True

End Sub

关于vba - 如何在同一工作表Excel VBA中复制列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43597734/

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