尝试将工作表中的范围复制到新工作簿中。 Excel VBA
Trying to copy Range from worksheet into a new workbook. Excel VBA
这是我的资料:
Sub exportDataAM()
Dim wbS As Workbook, wbT As Workbook
Dim wsS As Worksheet, wsT As Worksheet
Set wbS = ThisWorkbook 'workbook that holds this code
Set wsS = wbS.Worksheets("Recap").Range("A1:R5")
wsS.Copy
Set wbT = ActiveWorkbook 'assign reference asap
Set wsT = wbT.Worksheets("Recap").Range("A1:R5")
wsT.Name = "Recap" 'rename sheet
wbT.SaveAs wbS.Path & "\" & "Recap AM" & Format(Now, " dd-mm-yyyy ") 'save new workbook
End Sub
我得到一个类型不匹配,这对我来说对第 6 行的 .Range 没有意义。我知道还有其他方法可以做到这一点,但没有 .Range 也能正常工作,我想弄清楚为什么会这样。
如有任何帮助,我们将不胜感激。
您已将变量 wsS
和 wsT
声明为工作表。然而,您尝试在变量中添加一个范围。这将导致不匹配。
要么将变量声明为 Range
,要么只将工作表添加到变量中。
以下应该有效
Private Sub Copy()
Set newBook = Workbooks.Add
With newBook
.Title = "Recap Am"
.Subject = "RFQ"
.SaveAs Filename:="Recap.xls"
Dim rng As Excel.Range
Set rng = ThisWorkbook.Worksheets("SheetName").Cells.SpecialCells (xlCellTypeVisible)
rng.Copy newBook.Worksheets("Sheet1").Range("A1")
End With
End Sub
这是我的资料:
Sub exportDataAM()
Dim wbS As Workbook, wbT As Workbook
Dim wsS As Worksheet, wsT As Worksheet
Set wbS = ThisWorkbook 'workbook that holds this code
Set wsS = wbS.Worksheets("Recap").Range("A1:R5")
wsS.Copy
Set wbT = ActiveWorkbook 'assign reference asap
Set wsT = wbT.Worksheets("Recap").Range("A1:R5")
wsT.Name = "Recap" 'rename sheet
wbT.SaveAs wbS.Path & "\" & "Recap AM" & Format(Now, " dd-mm-yyyy ") 'save new workbook
End Sub
我得到一个类型不匹配,这对我来说对第 6 行的 .Range 没有意义。我知道还有其他方法可以做到这一点,但没有 .Range 也能正常工作,我想弄清楚为什么会这样。
如有任何帮助,我们将不胜感激。
您已将变量 wsS
和 wsT
声明为工作表。然而,您尝试在变量中添加一个范围。这将导致不匹配。
要么将变量声明为 Range
,要么只将工作表添加到变量中。
以下应该有效
Private Sub Copy()
Set newBook = Workbooks.Add
With newBook
.Title = "Recap Am"
.Subject = "RFQ"
.SaveAs Filename:="Recap.xls"
Dim rng As Excel.Range
Set rng = ThisWorkbook.Worksheets("SheetName").Cells.SpecialCells (xlCellTypeVisible)
rng.Copy newBook.Worksheets("Sheet1").Range("A1")
End With
End Sub