在VBA中循环单元格。

我正在努力使自己的代码更好,因为每个初学者都有问题使其更“系统化”,所以我想请教你如何去做。

我打开几个工作簿,所以现在我的macros看起来像这样。

Sub OpenWorkbooks() workbooks.Open Filename :="C/.../file1.xlsx" workbooks.Open Filename :="C/.../file2.xlsx" workbooks.Open Filename :="C/.../file3.xlsx" . . End sub 

它相当丑陋,我想在一个单元格中的每条path。 假设从A1到A3并循环这个单元格以打开工作簿。 任何想法我怎么能做到这一点?

在我的代码的其他部分,很好地发现在网上,我有同样的问题。 我希望能够在我的电子表格的某处input我的path,然后从那里循环,而不是一个接一个手动input…

这是代码的第二部分,相当无知我该怎么做…

 Sub GetNumber() Dim wWbPath As String, WbName As String Dim WsName As String, CellRef As String Dim Ret As String Workbooks("file1").Close SaveChanges:=True wbPath = "C:/etc...." WbName = "file1.xlsx" WsName = "Sheet1" CellRef = "AD30" arg = "'" & wbPath & "[" & wbName & "]" & _ wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1) Worksheets("Sheet1").Range("A1") = ExecuteExcel4Macro(arg) 'Then I need to do all again for the second workbook etc.... End sub 

任何想法是欢迎的,谢谢!

回答你的问题的第一部分:

  Sub OpenWorkbooks() For i = 1 to 3 ' Loop 3 times Workbooks.Open Filename:=Sheet1.cells(i,1).value 'Cells refers to Row and column, so i will iterate three times while keeping the column the same. Next i End sub 

如果您不知道要创build多less个循环,则可以使用以下方法检查数据和循环的最后一行,直到达到它:

 Sub OpenWorkbooks() LastRow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row For i = 1 to LastRow ' Loop as many times until the last row with data Workbooks.Open Filename:=Sheet1.cells(i,1).value 'Cells refers to Row and column, so i will iterate three times while keeping the column the same. Next i End sub 

对于代码的第二部分,您可以执行如下操作:

 Sub GetNumber() Dim wWbPath As String, WbName As String Dim WsName As String, CellRef As String Dim Ret As String For i = 1 to 5 'Change this to however many files you will be using FileName = Sheet1.cells(i,1).value Workbooks(FileName).Close SaveChanges:=True wbPath = "C:/etc...." WbName = FileName & ".xlsx" WsName = "Sheet1" CellRef = "AD30" arg = "'" & wbPath & "[" & wbName & "]" & _ wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1) Worksheets("Sheet1").Range("A" & i) = ExecuteExcel4Macro(arg) 'Then I need to do all again for the second workbook etc.... Next i End sub 

我不得不弄清楚最近怎么做类似的事情。 尝试这个 …

  Dim i As Long Dim SelectedFiles As Variant SelectedFiles = Application.GetOpenFilename("Excel Files (*.xlsx), *.xlsx", _ Title:="Select files", MultiSelect:=True) If IsArray(SelectedFiles) Then For i = LBound(SelectedFiles) To UBound(SelectedFiles) Set wbkToOpen = Workbooks.Open(Filename:=SelectedFiles(i), corruptload:=xlRepairFile) Debug.Print wbkToOpen.Name Debug.Print SelectedFiles(i) wbkToOpen.Close savechanges:=False Next End If