如何从名称列表中创建多个工作表,这些工作表是选定单元格的内容

时间:2012-05-02 23:42:39

标签: excel-vba vba excel

实际上,我只需要帮助提供一些关于Excel VBA的课程而不是代码。

问题

enter image description here

主要的代码是非常基本的,虽然我没有VBA经验,但我理解

Sheets.Add().Name = Name_of_Sheet

如果我定义了NameList =Array("SheetA", "SheetB", "SheetC","SheetD")之类的名称列表,那么请执行for循环

 For I = LBound(NameList) To UBound(NameList) 
    Sheets.Add().Name = Tabs(I) 
 Next I 

但是,很多时候,有标准的命名表,去Visual Basic编辑宏不是很有效。我想从单元格中创建表单。含量

我的问题

1)所选数据的索引(1D列,1D行或多行x多列)如何工作?

2)我如何访问这些单元格'内容?

4 个答案:

答案 0 :(得分:3)

你的问题很开放。这是一个解决“1D列”方面的开始。有很多方法可以做到这一点,但我已经包含了几个基本的VBA结构,比如For EachWith/End With。您可以轻松地将变量指向其他工作簿,工作表或单元格。它有一些错误处理来解决尝试使用已经存在的工作表名称的问题:

Sub AddSheets()
Dim cell As Excel.Range
Dim wsWithSheetNames As Excel.Worksheet
Dim wbToAddSheetsTo As Excel.Workbook

Set wsWithSheetNames = ActiveSheet
Set wbToAddSheetsTo = ActiveWorkbook
For Each cell In wsWithSheetNames.Range("A2:A5")
    With wbToAddSheetsTo
        .Sheets.Add after:=.Sheets(.Sheets.Count)
        On Error Resume Next
        ActiveSheet.Name = cell.Value
        If Err.Number = 1004 Then
          Debug.Print cell.Value & " already used as a sheet name"
        End If
        On Error GoTo 0
    End With
Next cell
End Sub

另一种方法是将单元格内容加载到一个数组中,如果它实际上是二维的(如果有大量的名称)可能会有用,但它也可能有点过分。

答案 1 :(得分:1)

感谢道格,这很棒。轻微的mod以避免重新命名范围:

    'select list range before running procedure
Sub AddSheets()
Dim cell As Excel.Range
Dim wbToAddSheetsTo As Excel.Workbook

Set wbToAddSheetsTo = ActiveWorkbook
For Each cell In Selection
    With wbToAddSheetsTo
        .Sheets.Add after:=.Sheets(.Sheets.Count)
        On Error Resume Next
        ActiveSheet.Name = cell.Value
        If Err.Number = 1004 Then
          Debug.Print cell.Value & " already used as a sheet name"
        End If
        On Error GoTo 0
    End With
Next cell
End Sub

答案 2 :(得分:1)

我根据自己的需要使用它:

Sub C_CreateEmptySheets()
    Dim MyCell As Range, MyRange As Range

    'This Macro will create separate tabs based on a list in Distribution Tab A2 down

    Set MyRange = Sheets("Distribution").Range("A2")
    Set MyRange = Range(MyRange, MyRange.End(xlDown))


    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    For Each MyCell In MyRange
        Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
        Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
    Next MyCell

    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub

答案 3 :(得分:-1)

with sheets
     .add.name="SheetA"
     .add.name="SheetB"
     .add.name="Sheetc"
end with