将单元格值复制到下一个空行到另一个工作簿vba

时间:2017-03-02 11:27:56

标签: excel vba

我有两个单独的Excel文件。其中一个在Sheet1中存储有关订单和订单号的信息。现在每次我发新订单时,我都希望从我的订单中收集这些信息并插入到所谓的“数据库”工作簿中。它应标识A列中的最后一个空行:Y = np.array(([3,5], [5,1], [10,2], [6,1.5]), dtype=float) Y array([[ 3. , 5. ], [ 5. , 1. ], [ 10. , 2. ], [ 6. , 1.5]]) 中的A,并将范围C:\Users\user\Desktop\Order_number.xlsx中的新值插入下一个空行。这是我提出的代码,但有一些错误,它不起作用。如何解决?

("C6,C17,C10,H18,B32,G32,H6,H9")

1 个答案:

答案 0 :(得分:1)

一些更正:

1)Set wsData = Workbooks("C:\Users\user\Desktop\Order_number.xlsx").Sheets("Sheet1")无效。如果工作簿已打开,请使用Set wsData = Workbooks("Order_number.xlsx").Sheets("Sheet1")。或者您需要先打开工作簿。

2)我并不喜欢使用Application.WorksheetFunction.CountA(wsData.Range("A:A"))获取最后一行。要获得A列中的最后一行(可能在中间跳过balnk单元格),请使用wsData.Cells(wsData.Rows.Count, "A").End(xlUp).Row

3)我的偏好是使用复制>> PasteSpecial xlPasteValues cl.Copy和以下行wsData.Range("A" & C).PasteSpecial xlPasteValues

<强>代码

Option Explicit

Sub TransferValues465()

Dim wsMain As Worksheet
Dim wbData As Workbook
Dim wsData As Worksheet
Dim rngToCopy As Range
Dim C As Long
Dim ar As Range
Dim cl As Range

Dim LastRow As Long
Dim rngDestination As Range

Set wsMain = ThisWorkbook.ActiveSheet

Application.DisplayAlerts = False
' you need to open the workbook
Set wbData = Workbooks.Open("C:\Users\user\Desktop\Order_number.xlsx")
Set wsData = wbData.Sheets("Sheet1")
Set rngToCopy = wsMain.Range("C6,C17,C10,H18,B32,G32,H6,H9")

'Get the last row in Database sheet:
LastRow = wsData.Cells(wsData.Rows.Count, "A").End(xlUp).Row

C = 1
For Each cl In rngToCopy
    cl.Copy
    wsData.Cells(LastRow + 1, C).PasteSpecial xlPasteValues
    C = C + 1
Next cl    

wbData.Close True '<-- close and save the changes made
Application.DisplayAlerts = True '<-- restore settings

End Sub