excel - VBa代码打开关闭的文件并复制列工作但什么也没做
问题描述
我有一个代码应该打开输入文件并从那里复制一些特定的列。这个宏没有显示任何错误它的工作但没有发生任何事情,我没有看到任何动作。我有 Excel 2016
Sub btnExport_Click()
Dim strPath As String
Dim wbMe, wb As Workbook
strPath = selectFile
If strPath = "" Then Exit Sub
Set wbMe = ActiveWorkbook
Set wb = Workbooks.Open(strPath, False, True)
wb.Sheets(1).Columns("A:C").Copy Destination:=wbMe.Sheets(1).Range("A1")
wb.Sheets(1).Columns("H").Copy Destination:=wbMe.Sheets(1).Range("D1")
wb.Close False
Set wb = Nothing
Beep
MsgBox "The data was imported"
End Sub
Private Function selectFile()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(3)
With fd
.InitialFileName = ActiveWorkbook.Path
.AllowMultiSelect = False
.Title = "Please select file to import."
.Filters.Clear
.Filters.Add "Excel", "*.xlsm"
If Show = True Then selectFile = .SelectedItems(1)
End With
End Function
解决方案
这是在您的工作表模块中:
Option Explicit
Sub btnExport_Click()
Dim strPath As String
Dim wbMe As Workbook, wb As Workbook
strPath = selectFile
If strPath = "" Then Exit Sub
Set wbMe = ActiveWorkbook
Set wb = Workbooks.Open(strPath, False, True)
copyRangeValues wb.Sheets(1).Columns("A:C"), wbMe.Sheets(1).Range("A1")
copyRangeValues wb.Sheets(1).Columns("H"), wbMe.Sheets(1).Range("D1")
wb.Close False
Set wb = Nothing
Beep
MsgBox "The data was imported"
End Sub
如果您还没有,请在您的项目中添加一个模块。
将以下函数粘贴到该模块
Option explicit
Public Function selectFile()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(3)
With fd
.InitialFileName = ActiveWorkbook.Path
.AllowMultiSelect = False
.Title = "Please select file to import."
.Filters.Clear
.Filters.Add "Excel", "*.xlsm"
If Show = True Then selectFile = .SelectedItems(1)
End With
End Function
Public Sub copyRangeValues(rgSource As Range, rgTargetCell As Range)
'generic routine to copy one range to another
'rgTargetCell = top left corner of target range
Dim rgTarget As Range
'resize rgTarget according to dimensions of rgSource
With rgSource
Set rgTarget = rgTargetCell.Resize(.Rows.Count, .Columns.Count)
End With
'write values from rgSource to rgTarget - no copy/paste necessary!!!
'formats are not copied - only values
rgTarget.value = rgSource.value
End Sub
推荐阅读
- javascript - 有没有办法使用 Webpack cli 捆绑没有 webpack.config.js 文件的 .js 文件?
- cmake - 如何在本地构建、安装和提供 CMake 包?
- c# - 如何读取 csv 文件并将其放入变量中以与 C# 中的给定值进行比较
- java - 从 Adapter 类访问 HashMap 数据
- javascript - 在 key 的动作被触发之前检测 contenteditable div 上的退格事件
- css - CSS:使Overflow-Y中的绝对项目始终填充滚动高度的100%
- c++ - “for(std::vector) 之间的奇怪区别
::iterator it = my_vec.begin(); 它!= my_vec.end(); ++it)" 和 "for(int i:my_vec)" - android - 从另一个屏幕返回后 Recyclerview 刷新 - Android 导航
- sql - 如何分隔/列出 varchar(max) 列中提到的单词
- laravel - Laravel 中基于 API 的观察者