首页 > 解决方案 > 将值粘贴到多列中的 VBA 代码

问题描述

我正在尝试编写一个 VBA 代码来复制和粘贴 CSV 文件中的多个列。目前我有以下代码:

Set thisWS = ActiveWorkbook.Sheets("Sheet1")
Set thatWB = Workbooks.Open("file_with_data.csv")
Set thatWS = thatWB.Sheets("table_with_data")
thatWS.Range("A2:X5000, Z2:Z5000, AC2:AC5000, AE2:AG5000").Copy
thisWS.Range("A4:X5002, Z4:Z5002, AC4:AC5002, AE4:AG5002").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

但是,当我运行它时,我收到以下错误消息:

Run-time error '1004'
That command cannot be used on multiple selections.
-> thisWS.Range("A4:X5002, Z4:Z5002, AC4:AC5002, AE4:AG5002").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

标签: excelvbacsv

解决方案


根据SJR的建议:

Sub UseArray()
    For Each a In Split("A2:X5000,Z2:Z5000,AC2:AC5000,AE2:AG5000", ",")
        With Range(a)
            .Copy
            .PasteSpecial Paste:=xlPasteValuesAndNumberFormats
        End With
    Next a
End Sub

(另一种方法是循环Areas


推荐阅读