将csv中的块数据粘贴到另一个excel文件中

时间:2016-10-26 15:53:06

标签: excel excel-vba vba

有没有办法不来回来选择工作簿并有效地复制数据块?

这就是我现在正在做的事情:

Set MyWB = ActiveWorkbook
Set DataWS = MyWB.Worksheets("Data")
Set TermDataRange = DataWS.Range("celltopaste")

Workbooks("data.csv").Activate
Range("A1").CurrentRegion.Copy  'selecting block data
MyWB.Activate
TermDataRange.Select
Selection.PasteSpecial Paste:=xlPasteValues

有没有选择MyWB的方法,那么范围?

另外,selection.paste感觉有点奇怪,我讨厌将数据复制到剪贴板。

我希望有类似的东西:

Workbooks("data.csv").Activate
TermDataRange = Range("A1").CurrentRegion

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

直接选择范围就像将三条线网格化一样简单:

Set TermDataRange = ActiveWorkbook.Worksheets("Data").Range("celltopaste")

编辑 - 我的错误 - 我跳过了比我想象的更多的步骤,实际上是将你的三条线而不是两条线压缩成一条:)

(老实说,我通常永远不会给ActiveWorkbook本身提供一个单独的名称,除非我需要在代码中稍后将其称为工作簿)

避免复制/粘贴非常简单。诀窍是确保您的源范围和目标范围是相同的大小和形状 - 一旦这是真的,您可以简单地使用代码

RangeA.Value = RangeB.Value

在您的情况下,最好的办法是先测量数据的大小。 e.g。

'give range("A1").current region a name just to make it less unwieldy
CopyRange = Range("A1").CurrentRegion
Datarows = CopyRange.Rows.Count
Datacols = CopyRange.Columns.Count
'set a range of same size starting from TermDataRange to move the values to
set DestRange = Range(TermDataRange, TermDataRange(offset(Datarows -1, Datacolumns -1))
'move values directly rather than via copy-paste
DestRange.Value = CopyRange.Value

答案 1 :(得分:1)

也许你正在寻找更多的东西"清洁"像这样?

Option Explicit

Sub CopyValueFromSheet()

    Dim MyWB As Workbook
    Dim DataWS As Worksheet
    Dim TermDataRange As Range
    Dim OtherWB As Workbook

    ' To avoid screen flashing
    Application.ScreenUpdating = False

    Set MyWB = ThisWorkbook
    Set DataWS = MyWB.Worksheets("Sheetname")
    Set TermDataRange = DataWS.Range("DestinationCell")

    Set OtherWB = Workbooks.Open("C:\Users\YourUsername\Desktop\CsvFileName.csv")
    ' When opening a csv file there is only one worksheet with the same name as the csv file
    OtherWB.Worksheets("CsvFileName").Range("SourceCell").Copy
    TermDataRange.PasteSpecial Paste:=xlPasteValues

    Application.ScreenUpdating = True

End Sub

修改 另一种可能的方法是将源单元的值存储在VBA变量中,然后将其设置为目标单元格,但它几乎相同:

    Dim VarValue As String
    VarValue = OtherWB.Worksheets("CsvFileName").Range("SourceCell").Value
    TermDataRange.Value = VarValue

HTH;)