确定。 我有以下代码让我崩溃Excel,但我无法弄清楚原因。我基本上使用了与我多次使用的完全相同的代码,没有任何问题。
基本上,我在两本不同的工作簿中都有姓氏和名字,如果它们彼此相等,我想将出生日期从一本工作簿复制到其他工作簿。
Sub Macro4()
Dim iRow As Integer, cRow As Integer
iRow = 4
Dim wbC As Workbook, wbA As Workbook, wsC As Worksheet, wsA As Worksheet
Set wbC = Workbooks("Coventry Enroll Census 113014")
Set wbA = Workbooks("Copy of Ameritas Enroll Census Template 1 1 15 (2).xls")
Set wsC = wbC.Sheets(1)
Set wsA = wbA.Sheets(2)
Do: cRow = 2 'Reset cRow
'DOB
If wsC.Cells(cRow, 2) = wsA.Cells(iRow, 2) And wsC.Cells(cRow, 1) = wsA.Cells(iRow, 3)Then
wsC.Cells(cRow, 10).Select
Selection.Copy
Range(wsA.Cells(iRow, 6)).PasteSpecial (xlPasteValues)
iRow = iRow + 1
Else
cRow = cRow + 1
End If
Loop Until wsC.Cells(cRow, 1) = "" And wsC.Cells(cRow + 1, 1) = "" And wsC.Cells(cRow + 2, 1) = ""
End Sub
答案 0 :(得分:1)
我认为你在每个循环开始时重置cRow
时创建了无限循环。因此,until
条件可能永远不会成立,因为cRow是2或3.我无法解释崩溃,但我认为它与此有关。尝试在循环的cRow = 2
之前设置Do
。
答案 1 :(得分:0)
尝试直接设置值而不是选择它们。我不能肯定地说如果没有你的工作簿和系统就能解决你的问题,但是试一试。
另外,请查看this link about avoiding using Select statements in VBA。
Do: cRow = 2 'Reset cRow
'DOB
If wsC.Cells(cRow, 2) = wsA.Cells(iRow, 2) And wsC.Cells(cRow, 1) = wsA.Cells(iRow, 3) Then
wsA.Cells(iRow, 6).Value = wsC.Cells(cRow, 10).Value 'THIS SETS ONLY THE VALUE.
iRow = iRow + 1
Else
cRow = cRow + 1
End If
Loop Until wsC.Cells(cRow, 1) = "" And wsC.Cells(cRow + 1, 1) = "" And wsC.Cells(cRow + 2, 1) = ""
End Sub
SIDE注意: 您打算在wbA中包含文件扩展而不是wbC吗?从你的代码:
Set wbC = Workbooks("Coventry Enroll Census 113014")
Set wbA = Workbooks("Copy of Ameritas Enroll Census Template 1 1 15 (2).xls")
编辑备注:添加旁注。