我的代码中的For Next循环应该复制1行数据数据19列宽,一次一行,由于某种原因,源文件的第一行将复制两次(对于i = 1和i = 2)然后两次用于源数据中的第二行(i = 3和4)每个循环逐行增加行号变量。任何想法,我做错了,再次提前感谢任何帮助
选项明确
Sub CopyColumnTest()
Const FILE1 As String = "c:\users\john\documents\cvi - excel files\project - Cash Drawer Report\New Folder\PreFlashSales.xls"
Const FILE2 As String = "c:\users\john\documents\cvi - excel files\project - Cash Drawer Report\New Folder\2016 Flash Sales-JFP.xls"
Const Sheet1 As String = "Sheet1"
Const Sheet2 As String = "Actual"
Dim Col As Integer
Dim Col1 As Integer
Dim Col2 As Integer
Dim Col3 As Integer
Dim RowNum As Integer
Dim RowNum1 As Integer
Dim RowNum2 As Integer
Dim LastRow1 As Integer
Dim LastRow2 As Integer
Dim wb1 As Workbook, wb2 As Workbook
Dim i As Integer
i = 1
Col = 5
Col1 = 1
Col2 = 23
Col3 = 19
RowNum = 1
If wb1 Is Nothing Then Set wb1 = Workbooks.Open(FILE1)
If wb2 Is Nothing Then Set wb2 = Workbooks.Open(FILE2)
LastRow1 = wb1.Sheets(Sheet1).Cells(Rows.Count, "A").End(xlUp).row 'Last Row of Data in PreFlashSales Workbook
LastRow2 = wb2.Sheets(Sheet2).Cells(Rows.Count, "E").End(xlUp).row + 1 'Last Row of Data Previously Added in 2016 FlashSales-JFP
RowNum1 = LastRow2
With wb1.Sheets(Sheet1)
For i = 1 To LastRow1
*** wb2.Sheets(Sheet2).Range(wb2.Sheets(Sheet2).Cells(RowNum1, Col), wb2.Sheets(Sheet2).Cells(RowNum1, Col2)).Value = _
wb1.Sheets(Sheet1).Range(wb1.Sheets(Sheet1).Cells(RowNum, Col1), wb1.Sheets(Sheet1).Cells(RowNum & Col3)).Value ***
RowNum = RowNum + 1
RowNum1 = RowNum1 + 1
Next i
End With
End Sub
答案 0 :(得分:0)
在进行直接分配时,您不需要循环,只需批量分配值即可:
Sub CopyColumnTest()
Const FILE1 As String = "c:\users\john\documents\cvi - excel files\project - Cash Drawer Report\New Folder\PreFlashSales.xls"
Const FILE2 As String = "c:\users\john\documents\cvi - excel files\project - Cash Drawer Report\New Folder\2016 Flash Sales-JFP.xls"
Const Sheet1 As String = "Sheet1"
Const Sheet2 As String = "Actual"
Dim Col As Long
Dim Col1 As Long
Dim Col2 As Long
Dim Col3 As Long
Dim LastRow1 As Long
Dim LastRow2 As Long
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Col = 5
Col1 = 1
Col2 = 23
Col3 = 19
If wb1 Is Nothing Then Set wb1 = Workbooks.Open(FILE1)
If wb2 Is Nothing Then Set wb2 = Workbooks.Open(FILE2)
'assign the sheets to variables to save typing
Set ws1 = wb1.Sheets(Sheet1)
Set ws2 = wb2.Sheets(Sheet2)
LastRow1 = ws1.Cells(Rows.Count, "A").End(xlUp).Row 'Last Row of Data in PreFlashSales Workbook
LastRow2 = ws2.Cells(Rows.Count, "E").End(xlUp).Row + 1 'Last Row of Data Previously Added in 2016 FlashSales-JFP
With ws1
' when using With any object that is part of the with you just need to use '.' in front
ws2.Range(ws2.Cells(LastRow2, Col), ws2.Cells(LastRow1 + LastRow2, Col2)).Value = .Range(.Cells(1, Col1), .Cells(LastRow1, Col3)).Value
End With
End Sub
至于为什么要复制两行,请查看最后一部分。分配语句wb1.Sheets(Sheet1).Cells(RowNum & Col3))
您有一个&
而不是,
。应该是wb1.Sheets(Sheet1).Cells(RowNum, Col3))