Excel VBA复制范围和单元格
我正在尝试将数据从工作表A复制到工作表B 我想复制X列第4行到第13行的单元格范围(X=第13行数值最高的单元格列),并将复制的数值粘贴到工作表B的第4行到第13行 运行代码不会复制数据,我不会得到任何错误,但不会粘贴任何内容 有人可以看一下代码,看看我的错误在哪里:Excel VBA复制范围和单元格,vba,excel,Vba,Excel,我正在尝试将数据从工作表A复制到工作表B 我想复制X列第4行到第13行的单元格范围(X=第13行数值最高的单元格列),并将复制的数值粘贴到工作表B的第4行到第13行 运行代码不会复制数据,我不会得到任何错误,但不会粘贴任何内容 有人可以看一下代码,看看我的错误在哪里: Sub Daily() Dim dailySht As Worksheet 'worksheet storing latest store activity Dim recordSht As Worksheet '
Sub Daily()
Dim dailySht As Worksheet 'worksheet storing latest store activity
Dim recordSht As Worksheet 'worksheet to store the highest period of each day
Dim lColDaily As Integer ' Last column of data in the store activity sheet
Dim lCol As Integer ' Last column of data in the record sheet
Dim maxCustomerRng As Range ' Cell containing the highest number of customers
Dim CheckForDups As Range ' Used to find duplicate dates on the record Sheet
Dim maxCustomerCnt As Double ' value of highest customer count
Set dailySht = ThisWorkbook.Sheets("Sheet A")
Set recordSht = ThisWorkbook.Sheets("Sheet B")
With recordSht
lCol = .Cells(1, .Columns.Count).End(xlToLeft).column
End With
With dailySht
lColDaily = .Cells(1, .Columns.Count).End(xlToLeft).column
maxCustomerCnt = Round(Application.Max(.Range(.Cells(13, 1), .Cells(13, lColDaily))), 2)
Set maxCustomerRng = .Range(.Cells(13, 1), .Cells(13, lColDaily)).Find(What:=maxCustomerCnt, LookIn:=xlValues)
If Not maxCustomerRng Is Nothing Then
' Check the Record Sheet to ensure the data is not already there
Set CheckForDups = recordSht.Range(recordSht.Cells(13, 1), recordSht.Cells(13, lCol)).Find(What:=Round(maxCustomerRng.Value, 2), LookIn:=xlValues)
' If CheckForDups is Nothing then the date was not found on the record sheet. Therefore, copy the column
If CheckForDups Is Nothing Then
Range(Cells(4, maxCustomerRng), Cells(13, maxCustomerRng)).Copy
recordSht.Cells(4, lCol + 1).PasteSpecial xlPasteValues
recordSht.Cells(4, lCol + 1).PasteSpecial xlPasteFormats
End If
End If
End With
Set maxCustomerRng = Nothing
Set dailySht = Nothing
Set recordSht = Nothing
End Sub
您正在尝试在一组未舍入的数据中查找舍入值。CheckForDups始终为nothing您有: 然后这些对
ActiveSheet
的隐式引用在With
块中:
这些隐式ActiveSheet
引用使您的代码根据当前处于活动状态的工作表工作,这可能不是您想要的-FWIW(我管理的开源VBIDE外接程序项目)可以帮助您轻松地在项目中的任何位置找到它们:
解决方案可能会使用一个点来限定这些调用,这样它们就可以关闭dailySht
工作表对象:
.Range(.Cells(4, maxCustomerRng), .Cells(13, maxCustomerRng)).Copy
您是否尝试过单步执行代码(使用F8)?我的猜测是两个或初始if语句都给出了false,从而结束了该语句。这有助于缩小问题的范围,还可以让您看到每个变量的值。@Cyril实际上是复制整个列时正常工作的代码。我正试图修改它,以便只复制特定的单元格,这就是我得到的结果ng问题。所以我认为问题在于复制/粘贴功能。你认为呢?我认为问题在于复制和粘贴功能。当复制整个列而不是特定单元格时,代码工作正常。谢谢,但代码链接到recordSht按钮上的一个按钮,所以我猜这不应该是问题?@aab呃,这意味着ns
“工作表B”
/recordSht
是你的ActiveSheet
,这意味着你正在从你的目标工作表复制,这意味着这个答案就是你的解决方案。隐式活动工作表/工作簿引用很容易占到这个网站上VBA主题问题的30%,这是我将其作为Rubberduck检查的一个原因;-)
Range(Cells(4, maxCustomerRng), Cells(13, maxCustomerRng)).Copy
.Range(.Cells(4, maxCustomerRng), .Cells(13, maxCustomerRng)).Copy