excel vba代码,用于根据选项卡名称将选项卡复制到新工作簿

时间:2013-02-23 19:25:33

标签: excel-vba vba excel

我正在尝试创建一些VBA代码来执行以下操作:

  1. 特定文件夹包含多个Excel文件,每个标签的名称都是(比如说)城市。

  2. excel列表定义城市所属的国家/地区。 (A栏=伦敦,巴黎,波士顿,纽约和B栏= U-K,法国,美国,美国)

  3. 我希望代码循环遍历该文件夹并为每个国家/地区创建一个重新组合所有城市的附加文件(每个城市只有一个标签,但有多个文件)

  4. 到目前为止,我所尝试的任何内容似乎都无法发挥作用。

1 个答案:

答案 0 :(得分:0)

这个问题非常广泛,但这个基本逻辑可能有所帮助:

使用这篇文章了解如何遍历目录: Specify Additional Directory to Loop Through Excel/VBA

此代码模板应该足以让您开始使用。使用它,改进您的问题,我们可以帮助您进一步。

Option Explicit

Sub CopySomeSheets()

    ' Loop through directory as in Question of this post
    Dim wb As Workbook
    Dim ws As Worksheet

    Dim cityNameList() As Variant
    Dim cityName As Variant


    ' Pseudocode, next line is a dummy to make example code run
    Set wb = ActiveWorkbook
    ' For Each wb In directory, as from post above
        For Each ws In wb.Worksheets
            For Each cityName In cityNameList

                ' Could do this as a loop for each country or think a bit more and produce a smarter iteration with range lookup/2d array or somethnig to better match the shape of your data
                cityNameList = Range("A1:A10") ' List of cities are in this range
                If InStr(ws.Name, cityName) Then
                    ' Do stuff, i.e. save workbook with required name
                End If

            Next cityName
        Next ws
    ' Next wb




End Sub