使用范围将数据输入到文件名

时间:2016-06-17 20:28:26

标签: excel vba excel-vba

下午好。我一直遇到这个代码的问题。如果我允许打开excel工作簿,然后使用ActiveWorkbook.Close函数关闭它,它可以正常工作。如果我将.close函数注释掉,我会收到运行时错误。我希望所有工作簿都能打开并保持开放状态。

Sub openwb1()
    Dim EPath As String, EFile As String, EMo As String, EVar As String, lastrow As Long, counter As Long, EFound As String

    lastrow = Worksheets("Opener").Cells(Rows.Count, 1).End(xlUp).Row

For counter = 1 To lastrow

    EPath = "Q:\MY PATH\"
    EVar = Worksheets("Opener").Range("A" & counter).Value
    EMo = MonthName(DatePart("m", Now), True) & " " & DatePart("yyyy", Now) & "\"
    EFound = Dir(EPath & EVar & EMo & "*$*.xlsx")

    If EFound <> " " Then
       Workbooks.Open FileName:=EPath & EVar & EMo & "\" & EFound
       End If

    If Len(Dir(EPath & EVar & EMo, vbDirectory)) = 0 Then
        MkDir EPath & EVar & EMo
        End If

    'ActiveWorkbook.Close

Next counter
End Sub

2 个答案:

答案 0 :(得分:0)

尝试将EVar = Thisworkbook.Worksheets("Opener").Range("A" & counter).Value更改为lastrow = Worksheets("Opener").Cells(Worksheets("Opener").Rows.Count, 1).End(xlUp).Row

BTW,lastrow = Worksheets("Opener").Cells(Rows.Count, 1).End(xlUp).Row可以更改为Rows.Count,因为此工作簿中的每个工作表都具有相同的class SplitViewController: NSSplitViewController { dynamic var items = [String]() @IBOutlet var arrayController: NSArrayController! override func viewDidLoad() { super.viewDidLoad() items.append("One") items.append("Two") items.append("Three") // let master = self.splitViewItems[0].viewController as! MasterViewController master.arrayController = self.arrayController let detail = self.splitViewItems[1].viewController as! DetailViewController detail.arrayController = self.arrayController } 。您无需指定要计算的工作表。

答案 1 :(得分:0)

像这样(未经测试)

Sub openwb1()

    Dim EPath As String, EFile As String, EMo As String
    Dim EVar As String, lastrow As Long, counter As Long, EFound As String
    Dim wb As Workbook

    lastrow = Worksheets("Opener").Cells(Rows.Count, 1).End(xlUp).Row

    'next two lines do not need to be inside the loop
    EPath = "Q:\MY PATH\"
    EMo = MonthName(DatePart("m", Now), True) & " " & DatePart("yyyy", Now) & "\"

    For counter = 1 To lastrow

        EVar = Worksheets("Opener").Range("A" & counter).Value

        If Len(Dir(EPath & EVar & EMo, vbDirectory)) = 0 Then

            MkDir EPath & EVar & EMo

        Else
            'only check for a file if the source folder was found...
            EFound = Dir(EPath & EVar & EMo & "*$*.xlsx")

            If EFound <> "" Then
                Set wb = Workbooks.Open(Filename:=EPath & EVar & EMo & "\" & EFound)

                'do something with wb

                wb.Close False 'don't save changes?

            End If

        End If

    Next counter

End Sub