在VBA中循环单元格。

时间:2017-12-05 16:04:21

标签: excel vba excel-vba loops

我正在努力使我的代码更好,因为每个初学者我都有问题使它更“系统化”,我希望你的建议如何做到这一点。

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

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

它非常难看,我想在一个单元格中拥有每条路径。让我们说从A1到A3并循环这个单元格来打开工作簿。知道我怎么能这样做吗?

在我的代码的另一部分,很好地在网上找到,我有同样的问题。我希望能够在我的电子表格中的某个地方输入我的路径,然后从那里循环,而不是逐个手动输入......

这是代码的第二部分,我不知道应该怎么做......

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  

欢迎任何想法, 谢谢!

2 个答案:

答案 0 :(得分:2)

回答问题的第一部分:

 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

如果您不知道要进行多少循环,可以使用以下内容检查上一行数据并循环直到找到它:

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  

答案 1 :(得分:0)

我不得不弄清楚最近有类似的事情。试试这个......

 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