在工作簿中循环用户定义的表格

时间:2015-04-29 09:07:40

标签: arrays vba loops

请检查我的问题......

关于工作簿:它有13张Sheet1是“Master”,其余12个被命名为月份“Apr”,“May”......等等......直到“Mar”.....

在“主”表中,用户可以定义他想要格式化的月份。用户可以定义像(“Apr”,“NA”,“Mar”)这样的值......代码应该读取用户输入的值并格式化仅匹配月份名称的表格并跳过NA。

守则应该做什么:

1)VBA应检查单元格O7到O18中的值,这些值是用户定义的值,如(Apr,Mar,Jan,NA)

2)然后代码应该转到名为apr to mar的工作表并跳过NA ..

Sub Copyd()
Dim apr As String
Dim may As String
    'Similarly for all the months till mar'
apr = Cells(7, 15).Value
may = Cells(8, 15).Value
    'Assigned cell value for all the month till mar(Cell contains values
     'like (Ex: apr,jan,NA) which are user defined
Dim Months As Variant
Dim Month As Variant
Months = Array(jan, feb, mar, apr, may, jun, jul, _
     aug, sep, oct, nov, dec)
ActiveSheet.Name = Months
For Each Month In Months
   'formatting code here
Next Month
End Sub

2 个答案:

答案 0 :(得分:1)

试试这个:

Dim wshSrc As Worksheet, wshDst As Worksheet
Dim i As Integer, wshName As String

On Error Resume Next

Set wshSrc = ThisWorkbook.Worksheets("Master")
For i = 7 to 18
    wshName = wshSrc.Range("O" & i)
    Set wshDst = ThisWorkbook.Worksheets(wshName)
    If Err.Number = 9 'worksheet does not exists (NA)
        Err.Clear()
        Goto SkipNext
    End If
    'here code to copy id's
SkipNext:    '
Next

答案 1 :(得分:0)

根据我的情况,这更好用。

Sub Copyd()
Sheets("Master").Select
Dim apr As String
Dim may As String

    'Similarly for all the months till mar'

apr = Cells(4, 56).Value
may = Cells(5, 56).Value

    'Assigned cell value for all the month till mar(Cell contains values
    'like: apr,jan,NA) which are user defined

Dim i As Long
For i = 3 To 13
With Sheets(i).Activate

If ActiveSheet.Name = apr Then
Call test
ActiveSheet.Name = apr
ThisWorkbook.Activate
Else
On Error Resume Next
End If

If ActiveSheet.Name = may Then
Call test
ActiveSheet.Name = may
ThisWorkbook.Activate
Else
On Error Resume Next
End If

   'Similarly for all the months till mar'

End With
Next i
End Sub