I am using this code which works fine on the same workbook.
Sub san_import(owb As Workbook, nwb As Workbook, sha As Worksheet, lis As String, col As Long, res As Long, Optional ByVal off As Long = 0)
Dim orng As ListObject
Dim nrng As ListObject
Dim r_fix As Long
Dim c_fix As Long
Dim i, o As Long
With owb
Set orng = sha.ListObjects(lis)
orng.AutoFilter.ShowAllData
End With
With nwb
Set nrng = sha.ListObjects(lis)
nrng.AutoFilter.ShowAllData
End With
r_fix = orng.ListRows.Count - nrng.ListRows.Count
c_fix = orng.ListColumns.Count - nrng.ListColumns.Count
With nwb
If r_fix > 0 Then
For i = 1 To r_fix
nrng.ListRows.Add AlwaysInsert:=True
Next i
End If
If c_fix > 0 Then
For o = 1 To c_fix
nrng.ListColumns.Add
Next o
End If
sha.Activate
sha.Range("A1").Select
End With
nrng.DataBodyRange.Offset(off).ClearContents
nrng.DataBodyRange.Offset(off).Columns(col).Resize(, res).Value2 = orng.DataBodyRange.Offset(off).Columns(col).Resize(, res).Value2
Application.StatusBar = "Processing " & sha.Name & "..."
End Sub
The problem arises when working with two different workbooks because the Listobject orng
is not successfully set for the old workbook. I have tried different variations including activating the old workbook first, but none worked. Any help would be much appreciated.
You are passing sha
as worksheet object , it must have always be either from owb or nwb.
To correct it, you can use sha.name
With nwb
Set nrng = sheets(sha.name).ListObjects(lis)
nrng.AutoFilter.ShowAllData
End With
Otherwise, you can pass the worksheet name as a String
And bind the listobject this way
With owb
Set orng = Sheets(sha).ListObjects(lis)
orng.AutoFilter.ShowAllData
End With
With nwb
Set nrng = Sheets(sha).ListObjects(lis)
nrng.AutoFilter.ShowAllData
End With
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.