VBA 打开多个工作簿,复制特定数据,删除重复行并将信息粘贴到新工作簿中

VBA to open several workbooks, copy specific data, remove duplicate rows and paste the information in a new workbook

我知道标题不是很清楚,但我希望我能在这个描述中更好地解释它。我是 VBA 的新手,我需要编写一些代码来执行以下操作:

。打开特定文件夹中的多个工作簿,并将源 sheet 中间的 table 中的信息(只有一个活动)复制到新工作簿中的目标 Sheet1。问题 1:tables 具有相同的列数但不同的行数(最初它们从 A42 到 L##(?) 不等,因为用户可以添加或删除行,或将它们留空)所以我所做的是在每个源文件中创建一个新的隐藏 sheet,它的第一个 A 列包含 1 和 0,这样我就可以知道我的副本的范围和 "pre-format" 我想传输到的信息目标文件)

。将每个源文件的隐藏 sheet 中的信息复制到目标工作簿,从目标工作簿 Sheet1 的第二行开始(对于正在复制的 table) - 第一行将有一个 pre-written header 提前 - 并在目标 sheet

的第一个可用空白行中保持粘贴来自下一个文件的信息

。删除重复行:如果用户多次运行宏,将看不到原始 tables 被复制了几次(还没有做到这一点)

我对 VBA 知之甚少,所以这就是我的进展 copy-pasting 我在网上搜索的不同内容(顺便说一句,代码没有按预期工作):

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)。你能帮我弄清楚如何纠正错误并结束代码吗?

替换

  wsSource.Range("B1:N" & lRow).Copy Destination:=wsTarget.Range("A" & NextRow0)

 wsSource.Range("B1:N" & lRow).Copy 
 wsTarget.Range("A" & NextRow0).pastespecial xlpastevalues

将您的数据从公式(即#REF)转换为值。假设您的其余代码可以解决问题