簡體   English   中英

協助 Excel VBA 參考單元格將工作表移動到新工作簿並保存

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM