简体   繁体   中英

How to open a workbook named after a cell in the worksheet?

I am trying to convert one txt file onto an excel one. I have the code for this. the problem is that my txt file will have a different name every day based on the date. therefore I have a cell in my workbook following the same name which I want to use to refer to the correct workbook.

When I press F5, I get a constant expression required error on the name of the file I call (line 3: " & varCellvalue & ".xls")

the name of the file I want to open is in C1.

Do you have any idea how to work around this error?

My code:

Sub Convert()
 DimvarCellvalue As Long
 varCellvalue = Range("C1").Value
    Const txtFldrPath As String = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & varCellvalue & ".xls"
    Const xlsFldrPath As String = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Payments Holidays"
    Dim CurrentFile As String: CurrentFile = Dir(txtFldrPath & "\" & "*.txt")
    Dim strLine() As String
    Dim LineIndex As Long
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    While CurrentFile <> vbNullString
        LineIndex = 0
        Close #1
        Open txtFldrPath & "\" & CurrentFile For Input As #1
        While Not EOF(1)
            LineIndex = LineIndex + 1
            ReDim Preserve strLine(1 To LineIndex)
            Line Input #1, strLine(LineIndex)
        Wend
        Close #1
        With ActiveSheet.Range("A1").Resize(LineIndex, 1)
            .Value = WorksheetFunction.Transpose(strLine)
            .TextToColumns Other:=True, OtherChar:="|"
        End With
        ActiveSheet.UsedRange.EntireColumn.AutoFit
        ActiveSheet.Copy
        ActiveWorkbook.SaveAs xlsFldrPath & "\" & Replace(CurrentFile, ".txt", ".xlsx"), xlOpenXMLWorkbook
        ActiveWorkbook.Close False
        ActiveSheet.UsedRange.ClearContents
        CurrentFile = Dir
    Wend
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

In this line

Const txtFldrPath As String = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & varCellvalue & ".xls"

You have declared the txtFldrPath as constant, so you can't use a variable with it varCellvalue Declare the varCellvalue as variable Dim txtFldrPath As String then assign the value as you wish

Dim txtFldrPath As String
txtFldrPath = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & varCellvalue & ".xls"

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