vba - VBA 打开多个工作簿,复制特定数据,删除重复行并将信息粘贴到新工作簿中
问题描述
我知道标题不是那么清楚,但我希望我能在这个描述中更好地解释它。我是 VBA 新手,我需要编写一些执行以下操作的代码:
. 打开特定文件夹中的多个工作簿并将信息从源工作表(只有一个活动)中间的表复制到新工作簿中的目标 Sheet1。问题 1:表格的列数相同但行数不同(最初它们从 A42 到 L##(?) 不同,因为用户可以添加或删除行,或者将它们留空)所以我所做的是创建一个新的每个源文件中的隐藏表都有第一个带有 1 和 0 的 A 列,因此我可以知道我的副本的范围并“预格式化”我想要传输到目标文件的信息)
. 将每个源文件的隐藏工作表中的信息复制到目标工作簿,从目标工作簿的 Sheet1 的第二行开始(对于正在复制的表) - 第一行将有一个预先写好的标题 - 并继续粘贴目标工作表第一个可用空白行中下一个文件的信息
. 删除重复行:如果用户多次运行宏,将不会看到原始表被复制多次(还没有到这一步)
我对 VBA 知之甚少,所以这就是我复制粘贴我在网上搜索的不同内容的过程(顺便说一句,代码没有按预期工作):
Sub ImportWorksheets()
Dim sFile As String 'file to process
Dim wsTarget As Worksheet
Dim wbSource As Workbook
Dim wsSource As Worksheet
'check the folder exists
If Not FileFolderExists(FOLDER_PATH) Then
MsgBox "Specified folder does not exist, exiting!"
Exit Sub
End If
'reset application settings in event of error
On Error GoTo errHandler
Application.ScreenUpdating = False
'set up the target worksheet
Set wsTarget = Sheets("Sheet1")
Dim NextRow0 As Long
NextRow0 = 2
'using NextRow0 to paste the new tables in in target sheet
'loop through the Excel files in the folder
sFile = Dir(FOLDER_PATH & "*.xls*")
Do Until sFile = ""
'open the source file and set the source worksheet - ASSUMED WORKSHEET(1)
Set wbSource = Workbooks.Open(FOLDER_PATH & sFile)
Set wsSource = wbSource.Worksheets(2) 'EDIT IF NECESSARY
Dim lRow As Long
lRow = wsSource.Columns("A").Find(1, SearchDirection:=xlPrevious, LookIn:=xlValues, LookAt:=xlWhole).Row
wsSource.Range("B1:N" & lRow).Copy Destination:=wsTarget.Range("A" & NextRow0)
NextRow0 = wsTarget.Range("A100000").End(xlUp).Row
'close the source workbook, increment the output row and get the next file
wbSource.Close SaveChanges:=False
sFile = Dir()
Loop
errHandler:
On Error Resume Next
Application.ScreenUpdating = True
'tidy up
Set wsSource = Nothing
Set wbSource = Nothing
Set wsTarget = Nothing
End Sub
现在代码没有将信息粘贴为值,而是路径,并且没有复制正确的信息(第二列返回#REF)。你能帮我弄清楚如何纠正错误并结束代码吗?
解决方案
replace
wsSource.Range("B1:N" & lRow).Copy Destination:=wsTarget.Range("A" & NextRow0)
with
wsSource.Range("B1:N" & lRow).Copy
wsTarget.Range("A" & NextRow0).pastespecial xlpastevalues
to turn your data from formulas (ie #REF) into values. Assuming the rest of your code works that ought to fix things
推荐阅读
- operator-overloading - 如何定义“AT-POS”方法?
- ruby - Ruby 应用程序的 Dockerfile - 为什么将 WORKDIR 指定为 /usr/src/app
- python-3.x - 在 Python 中使用 contenteditable
- python - scipy和numpy sobel梯度计算的区别
- python - 在 pybind11 中使用 opencv 类型
- android - OnActivityResult 没有在从适配器类传递意图的片段中被调用
- wordpress - 如何提交在woocommerce中选择的支付网关单选按钮?
- c# - 将集合绑定到 WPF 中的 ListBox
- mongodb - 文档中所有数组大小的MongoDB总和
- docker - Docker PowerCLI exec 用户进程导致“exec 格式错误”