Excel宏VBA 我在excel文件中有两张数据。我想循环遍历所有列和所有行以检查单元格是否为空。
我正在尝试替换“TemplateSheet”中的单词 “DataSheet”包含要替换的单词。
但似乎我的while循环无法循环遍历列。你能帮忙吗?
While Sheets("DataSheet").Cells(1, iColumn) <> ""
While Sheets("DataSheet").Cells(iRow, 1) <> ""
Dim sReplace As String
sReplace = Sheets("DataSheet").Cells(iRow, 1)
sTemplate = Sheets("TemplateSheet").Cells(1, 1)
sFind = Sheets("DataSheet").Cells(1, iColumn)
sTemplate = Replace(sTemplate, sFind, sReplace)
MsgBox sTemplate
iRow = iRow + 1
Wend
iColumn = iColumn + 1
Wend
感谢您的帮助。
答案 0 :(得分:1)
如果你真的想要一直到空白,那么就有一个CurrentRegion属性可以做到这一点。
Sub ReplaceCells()
Dim rCell As Range
Dim shTemplate As Worksheet
Dim shData As Worksheet
Dim sReplace As String, sTemplate As String, sFind As String
Set shTemplate = Sheets("TemplateSheet")
Set shData = Sheets("DatatSheet")
For Each rCell In shData.Range("A1").CurrentRegion.Cells
If Len(rCell.Value) > 0 Then
sReplace = shData.Cells(rCell.Row, 1)
sTemplate = shTemplate.Cells(1, 1)
sFind = shData.Cells(1, rCell.Column)
sTemplate = Replace(sTemplate, sFind, sReplace)
MsgBox sTemplate
End If
Next rCell
End Sub
答案 1 :(得分:0)
因此,您循环遍历列,然后循环遍历行。但是,当您到达下一列时,您的行永远不会被设置回1。是否可以解决您在行循环之前添加iRow = 1
的问题?
While Sheets("DataSheet").Cells(1, iColumn) <> ""
iRow = 1
While Sheets("DataSheet").Cells(iRow, 1) <> ""
Dim sReplace As String
sReplace = Sheets("DataSheet").Cells(iRow, 1)
sTemplate = Sheets("TemplateSheet").Cells(1, 1)
sFind = Sheets("DataSheet").Cells(1, iColumn)
sTemplate = Replace(sTemplate, sFind, sReplace)
MsgBox sTemplate
iRow = iRow + 1
Wend
iColumn = iColumn + 1
Wend