【发布时间】:2017-04-17 08:19:35
【问题描述】:
我遇到的这个问题包含三个文件:
“本地销售”、“全球销售”和“模板”。
销售文件的第 1 列和第 2 列是相同的,3 列各有不同的信息。所有这些数据都必须复制到“模板”中的工作表中。
第 1 列和第 2 列必须复制到相同的位置(第 1 列和第 2 列),第 3 列必须是本地销售文件中的第 3 列,第 4 列必须是全球销售文件中的第 3 列。跟我到现在?我希望如此...
这个例程第一次运行时一切顺利。它迭代第一个源文件中的所有列并将它们粘贴到模板上。但是当 fileNumber = 2 时(当它应该对第二个源文件做同样的事情时),标记的行声称“需要一个对象”。 这让我发疯了,因为我看不出它第一次起作用但第二次不起作用的原因!
我知道使用“激活”之类的命令是错误的,但这是我第一次使用 VBA,这是我看到的第一件事。请原谅它:)
Sub OpenFiles(ByVal fileNumber)
If fileNumber = 1 Then
Dim localFile As Workbook
Set localFile = Application.Workbooks.Open("local sales.xls") ' here the path of "local sales.xls"
Dim templateFile As Workbook
Set templateFile = Application.Workbooks.Open("Template.xls") ' here the path of "Template.xls"
localFile.Sheets("Sheet1").Activate
Else
Dim globalFile As Workbook
Set globalFile = Application.Workbooks.Open("global sales.xls") ' here the path of "global sales.xls"
globalFile.Sheets("Sheet1").Activate
End If
Dim lastColumnOnSource, lastRow, lastColumnOnDestiny As Long
Dim textLastRow, textCol, areaToSelect, areaToPaste As String
lastColumnOnSource = (ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column)
lastRow = ActiveSheet.UsedRange.Rows.Count
textLastRow = CStr(lastRow)
For currentColumnOnSource = 1 To lastColumnOnSource
If fileNumber = 1 Then
localFile.Sheets("Sheet1").Activate
Else
globalFile.Sheets("Sheet1").Activate
End If
columnAsLetter = ColumnLetter(currentColumnOnSource)
Let areaToSelect = columnAsLetter & "1:" & columnAsLetter & textLastRow
Range(areaToSelect).Select
Selection.Copy
' Moving to the template, to paste the data
templateFile.Sheets("Data").Activate ' HERE IS THE ERROR
lastColumnOnDestiny = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Dim cell1, cell2 As String
Dim cell2AsRange As Range
For currentColumnOnDestiny = 1 To lastColumnOnDestiny
' I take the first cell ("header") on the column and compare it until it's header
' matches the header on the column that is being copied and paste it there
Let cell1 = columnAsLetter & "1"
Let cell2 = ColumnLetter(currentColumnOnSource) & "1"
If Range(cell1).Value = Range(cell2).Value Then
' select the column that cell 2 belongs on, to paste in it
Let areaToPaste = cell1 & ":" & cell2
Range(areaToPaste).Select
Range(areaToPaste).PasteSpecial
Exit For
End If
Next
Next
Application.CutCopyMode = False
'Application.ActiveWorkbook.Save
End Sub
【问题讨论】:
-
templateFile 在哪里声明?如果是局部变量,fileNumber 1 时不赋值。
-
那里出现错误 - 现已修复。
codeDim template As Workbook Set templateFile = Application.Workbooks.Open("Template.xls") ' 这里是 "Template.xls" 的路径code应该是codeDim templateFile As Workbook Set templateFile = Application .Workbooks.Open("Template.xls") ' 这里是“Template.xls”的路径code还是没有运行。 -
请更新您的问题,以便代码反映您的更改。通过这些更改,错误是否相同且位于同一位置?
-
我发表评论时代码已更改。是的,错误仍然存在于同一个地方。请问为什么投反对票?