我希望有人可以帮我一些我一直在研究的代码。
基本上我要做的是从工作簿1复制某些数据并将它们复制到Workbook 2中。
我正在复制的数据在Cell A9的Workbook 1中开始,范围是动态的。例如,它可能从A9开始,有10个值,范围低至A18,但这一直在变化所以我需要确保循环在到达A列的最后一个值时停止。
我测试了下面的代码,它成功地将A9复制到A2。现在我正在尝试解决如何修改代码,以便从A9-A-n复制所有动态值。
TWBWS.Range("A2").Value = OWBWS.Range("A9").Value
以下是我到目前为止所尝试的内容。
Sub PopulateFields()
Workbooks("BUPA_LHC_Reconciliation_20171018204045.xlsx").Activate
Workbooks("BUPA_LHC_Reconciliation_20171018204045.xlsx").Worksheets("Unconfirmed").Activate
Dim twbrow_number As Integer
Dim owbrow_number As Integer
Dim OWBLastRow As Integer
Dim TWB As Workbook 'This workbook
Dim OWB As Workbook 'Other workbook
Dim TWBWS As Worksheet 'Data
Dim OWBWS As Worksheet 'Report worksheet, in OWB
owbrow_number = 8
twbrow_number = 1
Set TWB = Workbooks("LHC Report Email test v1.0.xlsm")
Set OWB = Workbooks("BUPA_LHC_Reconciliation_20171018204045.xlsx")
Set TWBWS = TWB.Worksheets("Sheet1")
Set OWBWS = OWB.Worksheets("Unconfirmed")
OWBLastRow = OWBWS.Cells(Rows.Count, 1).End(xlUp).Row - 2
Do
DoEvents
owbrow_number = owbrow_number + 1
twbrow_number = twbrownumber + 1
TWBWS.Range(Cells(twbrow_number, 1)).Value = OWBWS.Range(Cells(owbrow_number, 1)).Value
Loop Until owbrow_number = OWBLastRow
End Sub
答案 0 :(得分:0)
将代码的最后一部分替换为:
OWBLastRow = OWBWS.Cells(OWBWS.Rows.Count, "A").End(xlUp).Row - 2
TWBWS.Cells(2, "A").Resize(OWBLastRow - 8, 1).Value = OWBWS.Cells(9, "A").Resize(OWBLastRow - 8, 1).Value
End Sub
这将一次复制整个范围。
复制值的语句也可以重写为
TWBWS.Range("A2:A" & OWBLastRow - 7).Value = OWBWS.Range("A9:A" & OWBLastRow).Value
如果您使用了
,那么循环方法将起作用TWBWS.Cells(twbrow_number, 1).Value = OWBWS.Cells(owbrow_number, 1).Value
您的问题是您不能将单个单元格引用作为参数传递给Range
。它需要是两个单元格引用(定义左上角和右下角),或指定地址的字符串,或指定范围名称的字符串。