引用和复制
Application.GetOpenFilename
将返回文件 ( String
) 或False
( Boolean
) 的(完整)路径。这就是为什么你必须首先声明OldWorkbook
为 a的原因Variant
。因此使用引号 ( "False"
) 是不正确的。
- 假设结果(文件路径)
Application.GetOpenFilename
是C:\Test\Test.xlsx
.
在您的代码中,您实际上是在尝试做
Workbooks("C:\Test\Test.xlsx").Worksheets("PKG").Range("B12:CW28").Copy
(错误)而不是
Workbooks("Test.xlsx").Worksheets("PKG").Range("B12:CW28").Copy
(正确),因为Workbooks(...)
需要文件名,而Workbooks.Open(...)
需要文件路径。
- 解决这个问题的最好方法是实现一个工作簿变量,正如 BigBen 在评论中建议的那样,即在打开工作簿时创建对工作簿的引用。然后你不必关心文件名和文件路径,你只需在代码的延续中使用变量。
- 复制值时,通过赋值复制比使用更有效
PasteSpecial
(参见解决方案 2 和 3)。
Option Explicit
Sub VersionConvertQuickFix()
Dim wb As Workbook
Dim OldWorkbook As Variant
OldWorkbook = Application.GetOpenFilename("Excel Files (*.xl*),*.xl*", , "Choose File", "Open", False)
If OldWorkbook = False Then
Exit Sub ' To prevent an error from occurring when canceling the dialog.
Else
Set wb = Workbooks.Open(OldWorkbook)
End If
'Copy range to clipboard
wb.Worksheets("PKG").Range("B12:CW28").Copy
'PasteSpecial to paste values, formulas, formats, etc.
ThisWorkbook.Worksheets("PKG").Range("B12:CW28").PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
End Sub
Sub VersionConvert()
' Create a reference to the Source Range.
Dim swbPath As Variant
swbPath = Application.GetOpenFilename( _
"Excel Files (*.xl*),*.xl*", , "Choose File", "Open", False)
If swbPath = False Then
'MsgBox "Canceled."
Exit Sub
End If
Dim swb As Workbook: Set swb = Workbooks.Open(swbPath)
Dim srg As Range: Set srg = swb.Worksheets("PKG").Range("B12:CW28")
' Create a reference to the Destination Range.
Dim drg As Range: Set drg = ThisWorkbook.Worksheets("PKG").Range("B12:CW28")
' Copy by assignment (values only).
drg.Value = srg.Value
'swb.Close SaveChanges:=False
'drg.Worksheet.Parent.Save ' or ThisWorkbook.Save
End Sub
Sub VersionConvertDifferentDestinationAddress()
' Create a reference to the Source Range.
Dim swbPath As Variant
swbPath = Application.GetOpenFilename( _
"Excel Files (*.xl*),*.xl*", , "Choose File", "Open", False)
If swbPath = False Then
'MsgBox "Canceled."
Exit Sub
End If
Dim swb As Workbook: Set swb = Workbooks.Open(swbPath)
Dim sws As Worksheet: Set sws = swb.Worksheets("PKG")
Dim srg As Range: Set srg = sws.Range("B12:CW28")
' Create a reference to the Destination Range.
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dws As Worksheet: Set dws = dwb.Worksheets("PKG")
Dim dfCell As Range: Set dfCell = dws.Range("A1") ' e.g.
Dim drg As Range: Set drg = dfCell.Resize(srg.Rows.Count, srg.Columns.Count)
' Copy by assignment (values only).
drg.Value = srg.Value
'swb.Close SaveChanges:=False
'dwb.Save
End Sub