excel - 循环遍历单元格范围
问题描述
该代码旨在遍历指定范围内的所有单元格。下面是部分代码。Rng
在 for 循环中使用似乎有错误。当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
与Variant
在 VBA 中一样,您需要为每个变量指定一个类型,否则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
. 而 aString
没有 aRange
所以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
推荐阅读
- docker - docker-compose 突然出现 I/O 错误
- git - 为 git difftool 标签(目录名称)“左”和“右”配置不同的名称?
- python - 在 Python 中使用 Samba 客户端将文件从 Linux 复制到 Windows
- oracle - Oracle Apex 卡模板指令 - 在循环中使用两个列值
- c++ - 我想在 c++ 中运行 cryptominisat,但由于未定义对
- vue.js - vue 无法查询子组件 DOM 元素的选择器
- reactjs - 我正在为动作编写测试用例,但在使用 jest 和酶的调度时收到了匿名函数
- android - 更改使用形状创建的按钮的背景
- typescript - 需要解释 `tsconfig` 文件中的 `declaration` 属性
- puppeteer - 从网站控制无头 chrome 实例