![](/img/trans.png)
[英]Excel 2003 VBA: Move a sheet into a new workbook that is referenced by a variable
[英]Assistance with Excel VBA Reference Cell to Move Sheet to new workbook and save
我浏览了这个论坛和其他论坛来创建一个代码来完成这个任务。 我以前没有 VBA 经验,所以请保持温和。
本质上,我希望发生的是用户填写 Excel 表单并单击一个按钮。 该按钮将引用在单元格 K4 中选择的内容,然后根据该选择,将隐藏的工作表复制到新工作簿中,然后提示用户进行保存。
我使用的代码是:
Private Sub RSM_Click()
Dim newWkbk As Workbook
Dim newWksht As Worksheet
Dim wksht As Worksheet
Dim test As String
If StrComp(Me.Range("K4").Text, "INTERNAL USB", vbTextCompare) = 0 Then
test = "RSM_InternalUSB"
ElseIf StrComp(Me.Range("K4").Text, "INTERNAL 24 HR", vbTextCompare) = 0 Then
test = "RSM_Internal24Hr"
Else
test = "RSM_External"
End If
For Each wksht In ThisWorkbook.Worksheets
If wksht.Name = test Then
wksht.Visible = xlSheetVisible
Set newWksht = wksht.Copy
newWksht.Name = "RSM Onboarding Guide"
Set newWkbk = newWksht.Parent
End If
Next wksht
Dim varResult As Variant
Dim ActBook As Workbook
'displays the save file dialog
varResult = Application.GetSaveAsFilename(FileFilter:= _
"Excel Files (*.xlsm), *.xlsm", Title:="RSM Guide", _
InitialFileName:="\\Onboarding\")
'checks to make sure the user hasn't canceled the dialog
If varResult <> False Then
ActiveWorkbook.SaveCopyAs Filename:=varResult
Exit Sub
End If
End Sub
但是我得到了一个
编译错误:预期的函数或变量
在Set newwksht = wksht.Copy
链上。 它不喜欢副本。
我什至不知道保存部分是否会起作用,因为我无法通过这个
可以试试这个:
If GetSheet(test, newWksht) Then
With newWksht
.Visible = xlSheetVisible
.Copy ' this will make a copy of the referenced sheet in a newly created workbook
ActiveSheet.Name = "new"
.Visible = xlSheetHidden
End With
Dim varResult As Variant
'displays the save file dialog
varResult = Application.GetSaveAsFilename(FileFilter:= _
"Excel Files (*.xls*), *.xls*", Title:="RSM Guide", _
InitialFileName:="\\Onboarding\")
With ActiveWorkbook ' reference the newly created workbook, which is the "active" one
'checks to make sure the user hasn't canceled the dialog
If varResult <> False Then .SaveAs Filename:=varResult
End With
End If
它使用这个GetSheet()
“helper”函数的地方:
Function GetSheet(shtName As String, retSht As Worksheet) As Boolean
Set retSht = Worksheets(shtName)
GetSheet = Not retSht Is Nothing
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.