如何使用VBA打开.csv文件并将范围复制粘贴到新的Excel工作簿

efzxgjgh  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(322)

我正在尝试使用vba为用户按下一个按钮,让他们选择一个.csv工作簿。然后代码将复制和粘贴一个范围到另一个打开的工作簿。这是我目前的代码:

Private Sub CommandButton1_Click()
FileToOpen = Application.GetOpenFilename _
(Title:="Open Report File", _
FileFilter:="Excel Files *.csv (*.csv),")
Dim sourceworkbook As Workbook
Dim currentworkbook As Workbook
Set currentworkbook = ThisWorkbook
Set sourceworkbook = Workbooks(FileToOpen)
sourceworkbook.Worksheets(1).Select.Range("B4:F4").Copy
currentworkbook.Activate
currentworkbook.Worksheets("Sheet1").Activate
currentworkbook.Worksheets("Sheet1").Range("B14:F14").Select
ActiveSheet.Paste
sourceworkbook.Close
Set sourceworkbook = Nothing
Set currentworkbook = Nothing
ThisWorkbook.Activate
Worksheets("Sheet1").Activate
Worksheets("Sheet1").Range("B14").Select
End Sub

但我得到“运行时错误'9”:下标超出范围”在以下步骤:
Set sourceworkbook = Workbooks(FileToOpen)
有没有更好的方法来实现这一目标?

8cdiaqws

8cdiaqws1#

从关闭的工作簿导入区域

Option Explicit

Private Sub CommandButton1_Click()
    
    Dim FilePath: FilePath = Application.GetOpenFilename( _
        FileFilter:="Excel Files (*.csv), *.csv", _
        Title:="Open Report File")
    
    If VarType(FilePath) = vbBoolean Then
        MsgBox "Canceled.", vbExclamation
        Exit Sub
    End If
    
    Dim swb As Workbook: Set swb = Workbooks.Open(FilePath)
    Dim sws As Worksheet: Set sws = swb.Sheets(1) ' the one and only
    Dim srg As Range: Set srg = sws.Range("B4:F4")
    
    Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
    Dim dws As Worksheet: Set dws = dwb.Sheets("Sheet1")
    Dim dfCell As Range: Set dfCell = dws.Range("B14")
    
    srg.Copy dfCell
    
    swb.Close SaveChanges:=False
    
    ' Probably not necessary:
    'If Not dwb Is ActiveWorkbook Then dwb.Activate
    'Application.Goto dfCell

    MsgBox "Range imported.", vbInformation

End Sub

相关问题