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

标签 vba excel

我有一个程序需要复制同一工作簿和工作表中的选定列。 当前代码会导致 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/

相关文章:

arrays - 将二维数组转换为VBA中的列表

vba - 抑制 Word 2013 VBA 脚本中不需要的跳跃/滚动

mysql - 使用 VBA 连接 WAMP MySQL

vba - Excel 2007 vba 宏 : error 9 subscript out of range

c# - C# 中的 Excel - 2 张纸有问题

c# - 使用 Microsoft.Office.Interop.Excel 从 excel 2010 中读取数据

vba - 更改 PowerPoint 直方图中图表标题的文本颜色

excel - 需要帮助在单个单元格中获取多个值,并在 excel 中满足条件

excel - 通过引用文件路径在用户表单中设置图像控件的值

excel - 在某个区域中找到满意的单元格,然后突出显示该单元格所在的行