det*_*lly 11 excel vba excel-vba excel-2010
我目前正在处理一个数据集,其格式为表格,带有标题.我需要做的是循环遍历特定列中的所有单元格并更改内容.通过对MSDN的研究,我想出了以下for循环
for i = 1 to NumRows
Cells(i,23).Value = "PHEV"
next i
Run Code Online (Sandbox Code Playgroud)
因此,这会将第23列中的所有单元格更改为"PHEV".但是,我没有构建我自己正在使用的表,因此我不能保证我感兴趣的列将是第23列.
我想实现类似于以下内容:
for i = 1 to NumRows
Cells(i,[@[columnHeader]]).Value = "PHEV"
next i
Run Code Online (Sandbox Code Playgroud)
当然,我知道这种语法不正确,但希望它足以说明我的目标.
Dav*_*ens 22
如果这实际上是一个ListObject表(从功能区中插入表),那么您可以使用表的.DataBodyRange对象来获取行数和列数.这会忽略标题行.
Sub TableTest()
Dim tbl As ListObject
Dim tRows As Long
Dim tCols As Long
Set tbl = ActiveSheet.ListObjects("Table1") '## modify to your table name.
With tbl.DataBodyRange
tRows = .Rows.Count
tCols = .Columns.Count
End With
MsgBox tbl.Name & " contains " & tRows & " rows and " & tCols & " columns.", vbInformation
End Sub
Run Code Online (Sandbox Code Playgroud)
如果您需要使用标题行,而不是tbl.DataBodyRange仅使用tbl.Range.
小智 16
假设您的表名为"Table1",您需要的列是"Column",您可以尝试这样做:
for i = 1 to Range("Table1").Rows.Count
Range("Table1[Column]")(i)="PHEV"
next i
Run Code Online (Sandbox Code Playgroud)
LS_*_*ᴅᴇᴠ 10
您可以在分配前搜索列:
Dim col_n as long
for i = 1 to NumCols
if Cells(1, i).Value = "column header you are looking for" Then col_n = i
next
for i = 1 to NumRows
Cells(i, col_n).Value = "PHEV"
next i
Run Code Online (Sandbox Code Playgroud)
小智 10
假设你的表被称为“Table1”,你的列被称为“Column1”,那么:
For i = 1 To ListObjects("Table1").ListRows.Count
ListObjects("Table1").ListColumns("Column1").DataBodyRange(i) = "PHEV"
Next i
Run Code Online (Sandbox Code Playgroud)