2

我有一个宏来创建一个新的工作表,根据另一个工作表中单元格的值命名该工作表(即sheet1.Range("F3").value)。

之后,我需要转到我的数据所在的同一工作簿中的另一张工作表,选择某些数据并将其传输到新工作表。

这是我用来创建新工作表并为其命名的代码。

sub createNewSheet()

    sheet_name_to_creat = sheet1.range("F3").value

    for rep = 1 to (worksheets.count)
        if lCase(Sheets(rep).name = Lcase(Sheet_name_to_create) Then
            MagBox "This Sheet already exists"
            exit sub
        end if
    next

    Sheets.add after:=sheets(sheets.count
    Sheets(ActiveSheet.Name).name=Sheet_name_to_create

end sub
4

2 回答 2

0

您可以声明工作表变量并将数据表和新添加的表放入其中。然后很容易操作任何一个上的数据。

Sub createNewSheet()

    Dim wsNew As Worksheet
    Dim wsData As Worksheet
    'Rename this sheet to the name of the sheet where your data is located
    Set wsData = ActiveWorkbook.Sheets("MyDataSheet")

    sheet_name_to_create = Sheet1.Range("F3").Value

    For rep = 1 To (Worksheets.Count)
        If LCase(Sheets(rep)).Name = LCase(Sheet_name_to_create) Then
            MagBox "This Sheet already exists"
            Exit Sub
        End If
    Next

    Sheets.Add after:=Sheets(Sheets.Count)
    Sheets(ActiveSheet.Name).Name = Sheet_name_to_create
    Set wsNew = ActiveWorkbook.ActiveSheet

    'Now grab the data from your data worksheet
    Dim myData As String
    myData = wsData.Range("A1").Value

    'Then put it in your newly added sheet
    wsNew.Range("A1").Value = myData

    wsData = Nothing
    wsNew = Nothing
End Sub
于 2013-06-07T14:10:00.240 回答
0

我将对上述声明进行一些编辑以使其更有效。我知道变化很小,但这应该可以。

Sub createNewSheet()

    Dim wsNew As Worksheet
    Dim wsData As Worksheet
    'Rename this sheet to the name of the sheet where your data is located
    Set wsData = ActiveWorkbook.Sheets("MyDataSheet")

    sheet_name_to_create = Sheet1.Range("F3").Value

    For rep = 1 To (Worksheets.Count)
        If LCase(Sheets(rep).Name) = LCase(Sheet_name_to_create) Then
            MagBox "This Sheet already exists"
            Exit Sub
        End If
    Next

    Set wsNew = Sheets.Add after:=Sheets(Sheets.Count)
    wsNew.Name = Sheet_name_to_create

    wsData.Range("A1:Z80").copy  'Change range here to whatever range you need to move to the new sheet
    wsNew.Range("A1").pastespecial xlPasteValuesAndNumberFormats  

    wsNew = Nothing

End Sub
于 2019-08-14T12:42:58.303 回答