我正在尝试从一个工作簿V0复制特定工作簿工作表中的格式,然后遍历一个文件夹并将其粘贴到其他工作簿中。
我遇到的问题是,当我尝试将ws1设置为源表之一时,出现对象未定义错误。 ws1在顶部定义。当我通过调试运行所有其他变量的代码时,函数调用很好,它们的定义方式相同。
Dim StrFile As String, SDir As String
Dim name As String
Dim Src_pg1 As String, Src_pg2 As String 'Source and Target sheets
Dim Trgt_pg1 As String, Trgt_pg2 As String
Dim ws1 As Worksheet, ws2 As Worksheet 'define worksheets
Dim ws3 As Worksheet, ws4 As Worksheet
Dim WshSource As Workbook
Dim WshTarget As Workbook
SDir = "dircectory"
StrFile = Dir(SDir + "\*")
Src_pg1 = "Homepage Update"
Trgt_pg1 = "Homepage"
Src_pg2 = "raw"
Trgt_pg2 = "sample"
Application.ScreenUpdating = False
Do While Len(StrFile) > 0
name = StrFile
Set WshSource = Workbooks.Open("directory\v0.xlsm", True, True)
Set WshTarget = Workbooks.Open(SDir + "\" + name, True, True)
Set ws1 = WshSource.Sheets(Src_pg1) '******* Where the error happens****
Set ws2 = WshTarget.Sheets(Trgt_pg1)
Set ws3 = WshSource.Sheets(Src_pg2)
Set ws4 = WshTarget.Sheets(Trgt_pg2)
ws1.Cells.Copy
ws2.Cells.PasteSpecial Paste:=xlPasteFormats 'Source format pasted
ws2.Cells.PasteSpecial Paste:=xlPasteComments 'Comments are pasted.
ws2.Cells.PasteSpecial Paste:=xlPasteValidation 'Validations are pasted
Application.CutCopyMode = False
'Application.Goto .Cells(1), 1
ws3.Cells.Copy
ws4.Cells.PasteSpecial Paste:=xlPasteFormats 'Source format pasted
ws4.Cells.PasteSpecial Paste:=xlPasteComments 'Comments are pasted.
ws4.Cells.PasteSpecial Paste:=xlPasteValidation 'Validations are pasted
Application.CutCopyMode = False
'Application.Goto .Cells(1), 1