4

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

问题

在此处输入图像描述

主线代码很基础,虽然没有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)所选数据(一维列、一维行或多行x多列)的索引如何工作?

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

4

4 回答 4

4

你的问题很开放。这是解决“一维列”方面的开始。有很多方法可以做到这一点,但我已经包含了几个基本的 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

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

于 2012-05-03T03:39:36.027 回答
1

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

    '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
于 2014-09-12T06:35:20.743 回答
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
于 2016-06-29T22:02:55.160 回答
-1
with sheets
     .add.name="SheetA"
     .add.name="SheetB"
     .add.name="Sheetc"
end with
于 2017-09-21T09:44:57.460 回答