[英]How do I iterate through a range of two columns and select both columns in a row at each step?
I am trying to automate the task of defining names. 我正在尝试自动化定义名称的任务。 Specifically, I have two columns A and B, with B being dependent: 具体来说,我有两列A和B,其中B是从属的:
A B
Label1 Data1
Label2 Data2
Label3 Data3
I want to select both columns in a defined range, and then iterate through it, defining column B with the name in Column A. I figured a FOR EACH construct would work, but I can't find anything about how Excel exactly reads each item in the FOR EACH. 我想选择一个已定义范围内的两列,然后对其进行遍历,使用列A中的名称定义列B。我认为可以使用FOR EACH构造,但是我找不到关于Excel如何准确读取每个项目的任何信息在每个。 Does it see both columns in the current row as one unit (this would probably be ideal for my purpose)? 它是否将当前行中的两列都视为一个单元(这对我而言可能很理想)? Does it iterate down one column then the other? 是否先迭代一列然后再迭代另一列? Does it iterate each column in the row, then move down? 是否会迭代行中的每一列,然后向下移动?
Ultimately, I will be doing this for 3 or 4 pairs of columns. 最终,我将针对3或4对色谱柱进行此操作。 They will be used in the end to populate labels or selection boxes in a userform. 最后,它们将用于在用户表单中填充标签或选择框。 For example, if you select from a ComboCox 'Bacon', the label dependent on it will populate as 'Eggs'. 例如,如果您从ComboCox的“培根”中选择,则依赖于它的标签将填充为“鸡蛋”。 IF you select 'Oatmeal', it populates 'Raisins'. 如果选择“燕麦片”,则会填充“葡萄干”。
I have large columns I want to link up, and figured a quick macro would make it faster. 我有想要链接的大列,并且想出一个快速宏可以使其更快。
Thanks 谢谢
CODE SO FAR: 这么远的代码:
Sub FeatureNumberAssignMk2()
'
' FeatureNumberAssignMk2 Macro
'
' Keyboard Shortcut: Ctrl+Shift+L
'
Dim myCells As Range
Set myCells = Selection
For Each Row In myCells
' THIS IS WHERE I AM NOT SURE WHAT IS BEING SELECTED
Row.CreateNames Top:=False, Left:=True, Bottom:=False, Right:= _
False
Next
End Sub
There is no need to loop. 无需循环。 If you select a range comprising two columns, then that command will create a name for each row, using the text in the first column. 如果选择包含两列的范围,则该命令将使用第一列中的文本为每一行创建一个名称。
myCells.Row.CreateNames Top:=False, Left:=True, Bottom:=False, Right:=False
...but I can't find anything about how Excel exactly reads each item in the FOR EACH... ...但是我找不到关于Excel如何准确地读取FOR EACH中每个项目的任何信息...
For your reference, this is an easy way to test how the For Each
will loop: 供您参考,这是测试For Each
将如何循环的简单方法:
Dim Cell As Range
Dim Rng As Range
Set Rng = Range("A1:B5")
For Each Cell In Rng
Debug.Print Cell.Address
Next Cell
The output to the immediate window is as follows: 即时窗口的输出如下:
$A$1
$B$1
$A$2
$B$2
$A$3
$B$3
$A$4
$B$4
$A$5
$B$5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.