vba 获取范围内单元格的值,将其存储为变量,然后下一个单元格,下一行(Excel)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35318253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:12:43  来源:igfitidea点击:

Get the value of a cell in range, store it a variable, then next cell, next row (Excel)

excelvbaexcel-vbarow

提问by mcadamsjustin

I'd like to get the value of a cell in a range and store it as a variable. And then set the value of another cell in another range as that variable. Then move on to the cell. After all the cells in the row are captured, I'd like to move to the next row and start again with the first cell and first variable. I can't figure out how to move to the next cell and then set the value in the new range to the variable. Here's what I got so far

我想获取某个范围内单元格的值并将其存储为变量。然后将另一个区域中另一个单元格的值设置为该变量。然后移动到单元格。捕获该行中的所有单元格后,我想移到下一行并从第一个单元格和第一个变量重新开始。我不知道如何移动到下一个单元格,然后将新范围中的值设置为变量。这是我到目前为止所得到的

Dim rng As Range
Dim row As Range
Dim cell As Range
Dim card1 As String
Dim card2 As String
Dim card3 As String
Dim card4 As String
Dim card5 As String
Dim valueRng As Range

Set rng = Range("A2:D4")
Set valueRng = ("F2:I4")


For Each row In rng.Rows
 For Each cell In row.Cells
 card1 = cell.Value
 'Set first variable
 'Code here for setting value of for first cell in valueRng

'Move to second cell
'get value
'set variable card2
'Set value of second cell in valueRng

Next cell  
Next row

回答by Rory

Use row and column counters instead of For each:

使用行和列计数器代替For each

Dim rng As Range
Dim row As Range
Dim cell As Range
Dim card1 As String
Dim card2 As String
Dim card3 As String
Dim card4 As String
Dim card5 As String
Dim valueRng As Range
Dim x as long
Dim y as long

Set rng = Range("A2:D4")
Set valueRng = Range("F2:I4")


For x = 1 to rng.Rows.Count
   for y = 1 to rng.Columns.Count

 card1 = rng.cells(x, y).Value
 'Set first variable
 'Code here for setting value of for first cell in valueRng
 valueRng.Cells(x, y).Value = card1

Next y  
Next x

Note that there are far simpler ways of populating one array from another when they are the same size and shape.

请注意,当数组的大小和形状相同时,从另一个数组填充一个数组的方法要简单得多。