[英]Loop through range of cells
該代碼旨在遍歷指定范圍內的所有單元格。 下面是部分代碼。 在 for 循環中使用Rng
似乎存在錯誤。 當Rng
被替換為指定范圍時,例如Range("A1:B20")
,它可以工作,但代碼在
Cells(cell2.Row, LastCol1 + 1) = Application.VLookup(Range("A2:A1000"), strFileToOpen.Range("A10:C10000"), 3)
Dim Rng, cell, cell1, cell2 As Range
Dim strFileToOpen As Variant
strFileToOpen = Application.GetOpenFilename _
(Title:="Please choose the File", _
FileFilter:="Excel Files *.xls* (*.xls*),")
If strFileToOpen = False Then
MsgBox "No file selected.", vbExclamation, "Sorry!"
Exit Sub
Else
Workbooks.Open Filename:=strFileToOpen
End If
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
Rng = Range(Cells(5, 2), Cells(LastRow, LastCol))
For Each cell2 In Rng
If Trim(cell2.Value) <> "" Then
Cells(cell2.Row, LastCol1 + 1) = Application.VLookup(Range("A2:A1000"), strFileToOpen.Range("A10:C10000"), 3)
End If
Next
請注意, Dim Rng, cell, cell1, cell2 As Range
僅聲明cell2 As Range
但Rng, cell, cell1
在 VBA 中聲明為Variant
您需要為每個變量指定一個類型,否則默認情況下它是Variant
:
Dim Rng As Range, cell As Range, cell1 As Range, cell2 As Range
此外, Rng
是Object
,因此必須使用Set
Set Rng = Range(Cells(5, 2), Cells(LastRow, LastCol))
最后確保您使用Option Explicit
因為您的變量LastCol1
和LastCol
未定義,因此被視為0
但不存在列0
計數以1
開頭。
確保使用有意義的變量名。 像cell
、 cell1
、 cell2
這樣的名字對於每個程序員來說都是一場噩夢。 每當你摔倒時,你需要給變量名編號,你可以確定你做錯了。
最后,您的變量strFileToOpen
只是文件的路徑,因為Application.GetOpenFilename
僅返回String
。 並且String
沒有Range
,因此strFileToOpen.Range("A10:C10000")
無法工作。
因此你需要做類似的事情
Dim OpenedWorkbook As Workbook
Set OpenedWorkbook = Workbooks.Open(Filename:=strFileToOpen)
並使用
OpenedWorkbook.Worksheets("SpecifySheetName").Range("A10:C10000")
所以像下面這樣
Dim strFileToOpen As Variant
strFileToOpen = Application.GetOpenFilename( _
Title:="Please choose the File", _
FileFilter:="Excel Files *.xls* (*.xls*),")
If strFileToOpen = False Then
MsgBox "No file selected.", vbExclamation, "Sorry!"
Exit Sub
Else
Dim OpenedWorkbook As Workbook
Set OpenedWorkbook = Workbooks.Open(Filename:=strFileToOpen)
End If
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("SheetName") 'or ThisWorkbook.ActiveSheet if the sheet name is not defined
Dim LastRow As Long
LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Dim WorkingRange As Range
Set WorkingRange = ws.Range(ws.Cells(5, 2), ws.Cells(LastRow, LastCol)) 'LastCol is not defined!
Dim Cell As Range
For Each Cell In WorkingRange
If Trim(Cell.Value) <> vbNullString Then
'LastCol is not defined!
ws.Cells(Cell.Row, LastCol1 + 1) = Application.VLookup(ws.Range("A2:A1000"), OpenedWorkbook.Worksheet("DefineWorksheetName").Range("A10:C10000"), 3)
End If
Next Cell
我找到了問題的解決方案。 請讓我知道是否有更有效的方式在下面寫
Cells(cellrng.Row, LastCol1 + 1).Formula = Application.VLookup(Cells(cellrng.Row, 1).Value, Workbooks("FileName.xlsx").Sheets("Sheet1").Range("A1:C10000"), 3, False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.