Макрос, запускаемый через папку, возвращает ошибку индекса вне диапазона - PullRequest
0 голосов
/ 20 марта 2019

Настройка - у меня есть макрос, который находится в файле Excel, когда я нажимаю кнопку, он будет 1) перейти в папку 2) Запустить код для всех файлов xlsx.

Проблема - я протестировал части кода, и он работает, но когда я делаю все это, это не так. Отладка выделяет раздел, который я скоро покажу.

Sub CommandButton1_Click()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
'SOURCE: www.TheSpreadsheetGuru.com

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog

'Optimize Macro Speed
  Application.ScreenUpdating = False
  Application.EnableEvents = False
  Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User
  Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)

    With FldrPicker
      .Title = "Select A Target Folder"
      .AllowMultiSelect = False
        If .Show <> -1 Then GoTo NextCode
        myPath = .SelectedItems(1) & "\"
    End With

'In Case of Cancel
NextCode:
  myPath = myPath
  If myPath = "" Then GoTo ResetSettings

'Target File Extension (must include wildcard "*")
  myExtension = "*.xlsx*"

'Target Path with Ending Extention
  myFile = Dir(myPath & myExtension)

'Loop through each Excel file in folder
  Do While myFile <> ""
        'Set variable equal to opened workbook
          Set wb = Workbooks.Open(Filename:=myPath & myFile)

        'Ensure Workbook has opened before moving on to next line of code
          DoEvents

        'Change First Worksheet's Background Fill Blue



     'This code below gave us the first column but if clicked twice we have a problem'

    ActiveSheet.Columns("A").Insert Shift:=xlToRight

    ActiveSheet.Columns("A").Insert Shift:=xlToLeft
    'Added the title Source 2 to A1'

    Range("A1").Value = "XX"

    Range("B1").Value = "XX"




    'Perform the Find/Replace All'

        Columns("I").Replace What:="XX", _
                                Replacement:="XX", _
                                LookAt:=xlPart, _
                                SearchOrder:=xlByRows, _
                                MatchCase:=False, _
                                SearchFormat:=False, _
                                ReplaceFormat:=False

     'Solution to the columns A and B

    **Dim arrData As Variant, LastRow As Long, i As Long, ws As Worksheet

        Set ws = ThisWorkbook.Sheets("newreport") 'change the name of the sheet to the one you are doing the code**

        With ws
            LastRow = .Cells(.Rows.Count, 3).End(xlUp).Row
            arrData = .Range("A2", .Cells(LastRow, "C")).Value
            For i = 1 To UBound(arrData)

    'Save and Close Workbook
      wb.Close SaveChanges:=True

    'Ensure Workbook has closed before moving on to next line of code
      DoEvents

    'Get next file name
      myFile = Dir
  Loop

'Message Box when tasks are completed
  MsgBox "Task Complete!"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

Есть одна строка кода, которая является проблемой,

**Dim arrData As Variant, LastRow As Long, i As Long, ws As Worksheet

    Set ws = ThisWorkbook.Sheets("newreport")

Как мне справиться с этой проблемой?

Я думаю, мне нужно переписать этот код

Dim arrData As Variant, LastRow As Long, i As Long, ws As Worksheet

    Set ws = ThisWorkbook.Sheets("report1538393886588") 'change the name of the sheet to the one you are doing the code

        With ws
            LastRow = .Cells(.Rows.Count, 3).End(xlUp).Row
            arrData = .Range("A2", .Cells(LastRow, "C")).Value
            For i = 1 To UBound(arrData)
                If arrData(i, 3) Like "XXX*" Then
                    arrData(i, 1) = "XX XXX"
                Else
                    arrData(i, 1) = "XXX XXX"
                End If
                If arrData(i, 3) Like "CSI*" Or arrData(i, 3) = vbNullString Then
                    arrData(i, 2) = vbNullString
                Else
                    arrData(i, 2) = Right(arrData(i, 3), Len(arrData(i, 3)) - 12)
                End If
            Next i
            .Range("A2", .Cells(LastRow, "C")).Value = arrData
        End With

      For Each cell In Range("B2", Range("B605536").End(xlUp))
    If Not IsEmpty(cell) Then
    cell.Value = Right(cell, Len(cell) - 2)
    End If
    Next cell
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...