如何在新添加的工作表上使用单元格?

时间:2016-01-31 13:57:41

标签: excel vba

我有以下代码。

 Dim a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q as Range
 Dim z As Integer
 z = Sheet17.Cells(2, 1).Value
  With Sheets.Add
    .Select
    .Name = "PIAF_Summary" & z
    .ScrollArea = "A1:G108"     
  End With


z = z + 1
Columns("B:F").ColumnWidth = 38
With Range("A1:G1")
.Merge
.Interior.ColorIndex = 23
.Value = "Project Name (To be reviewed by WMO)"
.Font.Color = vbWhite
.Font.Bold = True
.Font.Size = 13
 End With

With Range("A5:G5")
.Merge
.Interior.ColorIndex = 23
.Value = "Project Name (Basic Project Information)"
.Font.Color = vbWhite
.Font.Bold = True
.Font.Size = 13
End With

如何激活添加的表格?因为我想为新的表格单元格添加一个值。

1 个答案:

答案 0 :(得分:0)

首先,当你声明你的变量时:

Dim a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q As Range

您只声明q as range,其他声明为as Variant 因此,如果您要声明所有这些as Range,您应该这样做:

Dim a As Range, b As Range, c As Range, d As Range

关于您的问题,首先需要Set您的工作表才能更轻松地使用。

 Sub test()

    Dim a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q As Range
    Dim z As Integer
    Dim wb As Workbook
    Dim ws17 As Worksheet, wsNew As Worksheet

    Set wb = ThisWorkbook
    Set ws17 = wb.Sheets("Sheet17")

    z = ws17.Cells(2, 1).Value

    Set wsNew = Sheets.Add ' Declare your New Sheet in order to be able to work with after
    wsNew.Name = "PIAF_Summary" & z

    z = z + 1

    wsNew.Columns("B:F").ColumnWidth = 38
    With wsNew.Range("A1:G1")
            .Merge
            .Interior.ColorIndex = 23
            .Value = "Project Name (To be reviewed by WMO)"
            .Font.Color = vbWhite
            .Font.Bold = True
            .Font.Size = 13
     End With

    With wsNew.Range("A5:G5")
            .Merge
            .Interior.ColorIndex = 23
            .Value = "Project Name (Basic Project Information)"
            .Font.Color = vbWhite
            .Font.Bold = True
            .Font.Size = 13
    End With

    'Now you can copy data from Sheet17 to the New created Sheet:
    ws17.Range("A2:C3").Copy wsNew.Range("A2")

    End Sub