简体   繁体   中英

VBA EXCEL: Fixing “Runtime-error '9'”: Subscript out of range

I have the below code which attempts to open a file name which changes on a daily basis if the sheet is empty. The file name is always named as such:

  • "K:\\Shared\\Num\\Temp\\Available_list_" & Year(Now()) & Month(Now()) & Day(Now()) & ".txt"

The reason behind this is to automate the file activation instead of copying, pasting, and renaming the file every time. I have received this error when I updated the code to include the above mentioned path. Can someone point to me out where my error is? You may find the code below:

Private Sub UserForm_Initialize()
Application.ScreenUpdating = False
If IsEmpty(A_Regular.Range("A2")) Then

Dim TxtPath, TxtName As String

TxtPath = "K:\Shared\Num\Temp\Available_list_" & Year(Now()) & Month(Now()) & Day(Now()) & ".txt"
TxtName = Year(Now()) & Month(Now()) & Day(Now()) & ".txt"

Workbooks.OpenText Filename:=TxtPath, Origin:=437, StartRow:=1, _
DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=True, Semicolon:=False, Comma:=False, Space:=False, _
Other:=True, OtherChar:=",", FieldInfo:=Array(Array(1, 1), _
Array(2, 1), Array(3, 5), Array(4, 1), Array(5, 1)), TrailingMinusNumbers:=True
'-------------------------------------------------------------------------'
'                               Setup Sheet                               '
'-------------------------------------------------------------------------'
    With Workbooks(TxtName)
'-------------------------------------------------------------------------'
    Dim TotalFree, TotalFields As Double
        TotalFree = Application.WorksheetFunction.CountIf(Range("D:D"), "FREE")
        Range("A1:E" & TotalFree).Copy
    End With

    Workbooks("Matcher.xlsm").Activate
    Activation.Visible = True
    Activation.Activate

        With Activation
            Range("A:E").PasteSpecial
            Range("1:1").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
            Range("A1") = "GSM"
            Range("B1") = "Type"
            Range("C1") = "Date"
            Range("D1") = "Status"
            Range("E1") = "Number"
            Range("F1") = "Pattern"
            Call Encryption
        End With
    Activation.Cells.Clear
    Windows(TxtName).Close
    Control.Activate
    Activation.Visible = False
End If

    Application.WindowState = xlMinimized
    NumberManagement.Show 0
End Sub

You open a file named "Available_list_" & Year(Now()) & Month(Now()) & Day(Now()) & ".txt" (filename without path) but you try to reference the sheet by Year(Now()) & Month(Now()) & Day(Now()) & ".txt" without Available_list . A worksheet with this name of course does not exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM