Как активировать файл Excel, не зная полного имени? - PullRequest
0 голосов
/ 11 декабря 2018

Я загружаю файл Excel, который каждый день меняет имя со случайными числами в конце.

Я беру данные и копирую их в свой мастер-файл.У меня есть копия / вставка.

Есть ли другой способ кодирования, кроме Activesheet.Я не хочу, чтобы конкретный файл Excel открывался и выбирался при запуске макроса, поскольку обычно у нас открыто несколько файлов Excel.

Есть ли способ выбрать файл Excel, не зная полного имени?

Вот весь код, который у меня есть:

'*******************************************************************************
' Purpose:    Updates ...
' Change PartialWorkbookName and the value of cStrPartial (the string).
'*******************************************************************************
Sub PartialWorkbookName()
  Const cStrPartial As String = "Task_States_(Pivot)"
  Dim objWb As Workbook
  For Each objWb In Workbooks
    If Left(objWb.Name, Len(cStrPartial)) = cStrPartial Then Exit For
  Next
  If objWb Is Nothing Then GoTo NotFound
  With objWb
'*******************************************************************************
' Code in here

.ActiveSheet.Columns("A:A").Select
'going from horasphere data status+date, making it readable by converting it with the comma and pasting it into your masterfile table.
'have to find a way to have the macro find the file without a name as the name will always change.

    Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
        Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1 _
        ), Array(14, 1), Array(15, 1), Array(16, 1)), TrailingMinusNumbers:=True
    'this top part is to make the data readable by going into Data - Text to columns - etc

    'To copy paste the readable data into the masterfile to run the 1st macro
    Rows("1:1").Select
    Selection.Delete Shift:=xlUp
    'Selects all dirty cell in the worksheet that is currently opened only, may need to tweak this later on
    ActiveSheet.UsedRange.Select
    Selection.Copy

    'pastes it into the blank sheet
    Windows("macro").Activate
    Sheets(3).Select
    Range("A1").Select
    ActiveSheet.Paste

    'deletes the table (have to eventually put that at the beginning of my macro)
    Sheets(1).Select
    Rows("3:3").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Delete Shift:=xlUp


    Sheets(3).Select
    Rows("1:1").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Sheets(1).Select
    Range("A2").Select
    ActiveSheet.Paste
    Sheets(3).Select
    Cells.Select
    Selection.ClearContents
    Sheets(1).Select

'*******************************************************************************
  End With
  Set objWb = Nothing
Exit Sub
NotFound:
  MsgBox "Workbook not found."
End Sub
'*******************************************************************************

1 Ответ

0 голосов
/ 11 декабря 2018

Частичное имя рабочей книги

'*******************************************************************************
' Purpose:    Updates ...
' Change PartialWorkbookName and the value of cStrPartial (the string).
'*******************************************************************************
Sub PartialWorkbookName()
  Const cStrPartial As String = "Book_20"
  Dim objWb As Workbook
  For Each objWb In Workbooks
    If Left(objWb.Name, Len(cStrPartial)) = cStrPartial Then Exit For
  Next
  If objWb Is Nothing Then GoTo NotFound
  With objWb
'*******************************************************************************
' Code in here

'*******************************************************************************
  End With
  Set objWb = Nothing
Exit Sub
NotFound:
  MsgBox "Workbook not found."
End Sub
'*******************************************************************************

Вы можете уменьшить его (не рекомендуется) до следующего значения:

'*******************************************************************************
' Purpose:    Updates ...
' Change PartialWorkbookNameReduced and the value of cStrPartial (the string).
'*******************************************************************************
Sub PartialWorkbookNameReduced(): Const cStrPartial As String = "Book_20"
  Dim objWb As Workbook: For Each objWb In Workbooks
      If Left(objWb.Name, Len(cStrPartial)) = cStrPartial Then Exit For
    Next: If objWb Is Nothing Then GoTo NotFound
  With objWb
'*******************************************************************************
' Code in here

'*******************************************************************************
  End With: Set objWb = Nothing: Exit Sub
NotFound: MsgBox "Workbook not found."
End Sub
'*******************************************************************************

Дополнительно вы можете поместить строку Dim в первую строку, но она превышаетПредел в 80 символов, поэтому я этого не делал.

РЕДАКТИРОВАТЬ:

  • В TextToColumns я удалил все аргументы с параметрами по умолчанию.

  • Если вы сравните этот код с вашим кодом, вы увидите логику, как это было сделано.Таким образом, если возникает ошибка, вы можете легко вернуть деталь
    , в которой произошла ошибка.

  • Все, что происходит в загруженном файле, происходит на листе с именем «Лист1», междуследующие две строки:

With objWb.Worksheets("Sheet1")

End With
  • И то, что происходит в книге, где находится этот код, происходит между следующими двумя строками:
With ThisWorkbook

End With

'*******************************************************************************
' Purpose:    Updates ...
' Change PartialWorkbookName and the value of cStrPartial (the string).
'*******************************************************************************
Sub PartialWorkbookNamedsf()
  Const cStrPartial As String = "Task_States_(Pivot)"
  Dim objWb As Workbook
  For Each objWb In Workbooks
    If Left(objWb.Name, Len(cStrPartial)) = cStrPartial Then Exit For
  Next
  If objWb Is Nothing Then GoTo NotFound
'*******************************************************************************
  With objWb.Worksheets("Sheet1")
    ' going from horasphere data status+date, making it readable by converting
    ' it with the comma and pasting it into your masterfile table.
    ' have to find a way to have the macro find the file without a name as
    ' the name will always change.
    .Columns("A:A").TextToColumns Destination:=.Range("A1"), _
        Tab:=True, Comma:=True, TrailingMinusNumbers:=True, FieldInfo:= _
        Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), _
        Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), _
        Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), _
        Array(14, 1), Array(15, 1), Array(16, 1))
    ' this top part is to make the data readable by going into
    ' Data - Text to columns - etc

    ' To copy paste the readable data into the masterfile to run
    ' the 1st macro
    .Rows(1).Delete Shift:=xlUp

    ' Selects all dirty cell in the worksheet that is currently opened only,
    ' may need to tweak this later on
    .UsedRange.Copy

  End With

  With ThisWorkbook

    ' pastes it into the blank sheet
    .Sheets(3).Range("A1").Paste
    ' deletes the table (eventually put this at the beginning of my macro)
    .Sheets(1).Rows(3).End(xlDown).Delete Shift:=xlUp
    .Sheets(3).Rows(1).End(xlDown).Copy Destination:=.Sheets(1).Range("A2")
    .Sheets(3).Cells.ClearContents
    .Sheets(1).Select

  End With
'*******************************************************************************
  Set objWb = Nothing
Exit Sub
NotFound:
  MsgBox "Workbook not found."
End Sub
'*******************************************************************************
...