在当前目录中打开工作簿

时间:2019-02-28 07:33:46

标签: excel vba

我有一个主工作簿,其中包括文件flag = None # ---add for i in range(int(sys.argv[1]),int(sys.argv[2])): stdate = parser.parse(sys.argv[3]) todate = parser.parse(sys.argv[4]) while stdate <= todate: lctr += 1 if lctr == 1: if fctr % 100 == 0: print('creating sample' + str(fctr).rjust(5,"0") + '.txt') f = open("sample" + str(fctr).rjust(5,"0") + '.txt',"w") f.write(str(i) + ', ' + stdate.strftime('%m/%d/%Y') + ', 0800, A\r\n') f.write(str(i) + ', ' + stdate.strftime('%m/%d/%Y') + ', 1700, Z\r\n') if flag and flag != str(i): # ---add f.write('\n') # ---add flag = str(i) # ---add stdate = stdate + timedelta(days=1) if lctr == 180 : fctr += 1 lctr = 0 f.close() 的列表,其中一些是空白(空)单元格。我需要代码来遍历列表并打开列出的工作簿(所有工作簿都在当前目录中)。我尝试过此代码,但收到错误消息:

(E14:E26)

2 个答案:

答案 0 :(得分:2)

我想单元格不包含工作簿的完整路径,而仅包含文件名,因此应该可以工作:

    Sub SkipBlankCells()
        Dim cell As Range, rng As Range, FName As String

        Set rng = Range("E14:E26")

        For Each cell In rng
            If Not IsEmpty(cell) Then
                FName = vbNullString
                FName = Dir(thisworkbook.Path & "\" & cell.Value) 'use dir to get the filename. If it doesn't exists, it will return blank
                If Not FName = vbNullString then Workbooks.Open _
                   Filename:=Thisworkbook.Path & "\" & FName 'to open a workbook you need the whole path to it, not only the file name.
            End If
        Next cell
    End Sub

答案 1 :(得分:0)

该功能应该起作用。我认为您的职能问题是路径。为了解决我使用函数ActiveWorkbook.Path的问题,但仅供您了解,您可以使用文字路径,例如"C:\Users\bor\Documents\folder_with_files"来使用其他路径。

Sub open_file_list()
    first_row = 14 'in your case
    last_row = 26 'in your case
    For i = first_row To last_row
        If Not IsEmpty(Cells(i, 5)) Then 'Check for empty
            file = Cells(i, 5)
            Workbooks.Open (ActiveWorkbook.Path & "\" & file)
            End If
    Next

End Sub