我拼凑了一个子程序,从两个单独的工作表中的单元格块中获取两个数据范围。然后,使用.Copy
方法,将第一个块放入第三个工作表的(1, 1)
,将第二个块放入该工作表的下一个可用行。
我写的代码几乎完成了我想要它做的事情,除了由于某种原因它不会粘贴第二个范围(在下面声明为DataRng2
),除非sub连续运行两次。这就是我所拥有的:
Sub Test()
Dim DataRng As Range
Dim DataRng2 As Range
Dim Test As Worksheet
Dim EmtyRow As Range
Application.ScreenUpdating = False
Set Test = Worksheets("Test")
'Set the "EmptyRow" reference to whatever the next empty row is in the destination worksheet - checks column A
Set EmptyRow = Worksheets("Test").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
'Select all utilized cells in 82-Medicine tab and copy them
Worksheets("82-Medicine").Select
Set DataRng = Worksheets("82-Medicine").Cells(2, 1).CurrentRegion
'Select the destination worksheet and paste copied cells to A1
Test.Select
DataRng.Copy Cells(1, 1)
'Select all utilized cells in Fee Basis tab and copy them
Worksheets("Fee Basis").Select
Set DataRng2 = Worksheets("Fee Basis").Cells(2, 1).CurrentRegion
'Select the destination worksheet and paste copied cells to the next empty row
Test.Select
DataRng2.Copy EmptyRow
Application.ScreenUpdating = True
End Sub
为什么我必须运行两次以使其工作?有办法解决这个问题吗?
我应该注意,我使用.CurrentRegion
属性来获取数据只是因为数据行经常被添加到我需要抓取的单元格区域中并从中减去,.CurrentRegion
是我所知道的最简单的方法是抓住任何被占用的细胞的第一个范围。如果有必要,我愿意使用不同的属性或方法。
答案 0 :(得分:0)
Option Explicit
Sub Test()
Dim src_1 As Worksheet
Dim src_2 As Worksheet
Dim dest As Worksheet
Dim src_1_rng As Range
Dim src_2_rng As Range
Dim lr As Integer
Dim lc As Integer
Set src_1 = ThisWorkbook.Sheets("82-Medicine")
Set src_2 = ThisWorkbook.Sheets("FeeBasis")
Set dest = ThisWorkbook.Sheets("Test")
'' Set up range for data from '82-Medicine'
lr = src_1.Cells(2, 1).End(xlDown).Row
lc = src_1.Cells(2, 1).End(xlToRight).Column
Set src_1_rng = src_1.Range(src_1.Cells(2, 1), src_1.Cells(lr, lc))
'' Set up range for data from 'FeeBasis'
lr = src_2.Cells(2, 1).End(xlDown).Row
lc = src_2.Cells(2, 1).End(xlToRight).Column
Set src_2_rng = src_2.Range(src_2.Cells(2, 1), src_2.Cells(lr, lc))
'' Copy the data to the destination sheet ('Test')
src_1_rng.Copy dest.Range("A" & dest.Rows.Count).End(xlUp).Offset(1)
src_2_rng.Copy dest.Range("A" & dest.Rows.Count).End(xlUp).Offset(1)
End Sub
不确定为什么那不起作用,但试试这个。我从未成为CurrentRegion
的粉丝或在代码中选择不同的工作表。当你可以使用引用时,为什么还要烦恼?这应该是完美的。
修改的 将lr和lc变量更改为使用(2,1)中的xlDown和(2,1)中的xlToRight来正确获取“CurrentRegion” - 范围。