在Workbooks对象中连接索引名称

时间:2014-11-19 00:12:21

标签: excel vba

我正在尝试为几个工作簿创建For Each循环;但是我无法在数组中设置工作簿名称,从而导致了这一点。我一直试图连接工作簿名称。

这是我的代码:

 'Open all .csv file in folder location

    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object

    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Set objFolder = objFSO.GetFolder(ThisWorkbook.Path)

    For Each objFile In objFolder.Files
        If InStr(objFile, ".csv") Then
            Workbooks.Open (objFile)
        End If
    Next

    ' Declare variables
    Dim WrkBkPrm As Workbook
    Dim WrkBkSrc As Workbook
    Dim WrkShtPrm As Worksheet
    Dim WrkShtSrc As Worksheet
    Dim TextSrc(4) As String
    Dim SrcRng As Range
    Dim DRng As Range

   ' Assign values to TextSrc() Array
      TextSrc(0) = Cable
      TextSrc(1) = Care
      TextSrc(2) = MSD
      TextSrc(3) = Business

   'Set WrkBkPrm and WrkShtPrm values

   Set WrkBkPrm = Workbooks("MasterFile" & ".xlsm")
   Set WrkShtPrm = WrkBkPrm.Worksheets("Canvas")

   'Activate Canvas Sheet

   WrkBkPrm.Activate
   WrkShtPrm.Select
   Application.ScreenUpdating = False

   'Start For Each Loop
   For Each Src In TextSrc()

    Set WrkBkSrc = Workbooks(Src & ".csv")
    Set WrkShtSrc = WrkBkSrc.Worksheets(Src)

    'Copy loop for 1st section

    For i = 2 To 49
        For j = 7 To 25

        Set SrcRng = WrkShtSrc.Cells(i, j)
        Set DRng = WrkShtPrm.Cells(i, j)

        If SrcRng <> "" Then
        DRng.Value = SrcRng.Value
        End If

        Next j
    Next i

    Next Src

    Application.ScreenUpdating = True

1 个答案:

答案 0 :(得分:0)

我建议您在获得所需的相关信息后立即处理该文件 类似的东西:

Dim wb As Workbook

For Each objFile In objFolder.Files
    If InStr(objFile.Name, ".csv") <> 0 Then
        Set wb = Workbooks.Open(Thisworkbook.Path & "\" & objFile.Name)
        '~~> Do your cool stuff with the opened CSV File
        wb.Close False '~~> Close without saving
        Set wb = Nothing '~~> Clean up although most of the time not necessary
    End If
Next

至于您所使用的路线,您需要在TxtSrc上使用 For Each Loop ,您需要将其声明为变体。
类似的东西:

Dim TxtSrc As Variant, Src As Variant

TxtSrc = Array("Cable", "Care", "MSD", "Business")
For Each Src In TxtSrc
    Set wb = Workbooks.Open(Thisworkbook.Path & "\" & Src & ".csv")
    '~~> More cool stuff here
    wb.Close False
    Set wb = Nothing
Next

重要工作簿打开方法提供正确的参数。
您应始终以字符串格式包含完整路径。 HTH。