Excel列的变量,分配给变量的列

tf7tbtn2  于 2022-12-01  发布在  其他
关注(0)|答案(3)|浏览(228)

我有一个宏,它在当前工作表中插入2列,并粘贴另一个工作表中的信息。
我想创建2个变量,分配给每一列,下次运行宏将信息粘贴到下两列时,这些变量将发生变化。

Columns("BO:BO").Select

Selection.Insert Shift:=xlToRight

Range("BO2").Select
ActiveCell.FormulaR1C1 = "Feb weekly-wk 2"
Range("BO19").Select
ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(Comparison!RC2,'Jan16 wk4'!R3C15:R34C24,9,FALSE)"
Range("BO19").Select
Selection.AutoFill Destination:=Range("BO19:BO47"), Type:=xlFillDefault
Range("BO19:BO47").Select

Columns("BP:BP").Select

Selection.Insert Shift:=xlToRight
Range("BP2").Select
Selection.Style = "20% - Accent6"
Range("BP2").Select
ActiveCell.FormulaR1C1 = "Diff"
Range("BP19").Select
ActiveCell.FormulaR1C1 = "=RC[-2]-RC[-1]"

我的想法是设置一个变量,用它替换当前的“BO”和“BP”代码。

Dim X as String, Y as String

X = "BO"

y = "BP"

当我运行宏时,它会将此示例的变量“BO”更改为“BQ”,“BP”更改为“BR”。下次我运行宏时,它会将“BQ”更改为“BS”,“BR”更改为“BT”。

vlurs2pr

vlurs2pr1#

如果你不是真的将BO/BP写入你正在转换的范围,我会用两个整型,存储在一个隐藏的工作表中。每次运行宏时读/写。
在我看来,这是更简单的解决方案,其他地方可以去global variables或将其存储到文件中。

fhity93d

fhity93d2#

我只是稍微清理了一下代码:

Dim ColBO As Integer
Dim ColBP As Integer

Dim StrBO As String
Dim StrBP As String

StrBO = "BO"
StrBP = "BP"

ColBO = ActiveWorkbook.Range(StrBO & 1).Column 'instead of StrBO you could directly write ("BO" & 1)
ColBP = ActiveWorkbook.Range(StrBP & 1).Column 'Then you wouldnt need these two variables

Columns(ColBO).Insert Shift:=xlToRight
'Columns(ColBO).Select   ' Trying to avoid selection but not sure if this works here...
'Selection.Insert Shift:=xlToRight

Range(1, ColBO).FormulaR1C1 = "Feb weekly-wk 2"
Range(19, ColBO).FormulaR1C1 = "=VLOOKUP(Comparison!RC2,'Jan16 wk4'!R3C15:R34C24,9,FALSE)"
Range(19, ColBO).AutoFill Destination:=Range("BO19:BO47"), Type:=xlFillDefault

Columns(ColBP).Insert Shift:=xlToRight  'Same here as above
Range(2, ColBP).Style = "20% - Accent6"
Range(2, ColBP).FormulaR1C1 = "Diff"
Range(19, ColBP).FormulaR1C1 = "=RC[-2]-RC[-1]"

面向未来:如果可以,尽量避免。如果可能,选择/Selection/.Activate。代码大多数情况下可以在没有这些命令和不激活单元格的情况下运行。)

baubqpgj

baubqpgj3#

如果要使用数值变量,可以更改方法,使用Cells代替Range

'You can use the rows below to know the column number
Range("BO1").Activate
ActiveCell.Value = ActiveCell.Column 'This way you get the column number into the cell
ColNum = ActiveCell.Column 'This way you get the column number into the variable
'So now you know that BO column number is 67 and you can use
Cells(1, 67) = "OK"
'Or, using variables:
RowNum = 1
ColNum = 67
Cells(RowNum, ColNum) = "You Got It!"

这使得您能够简单地使用for ... next循环列
如果需要从业务对象循环到BR,可以使用

For ColNum = 67 To 70
    Cells(1, ColNum) = "OK"
Next ColNum

希望能有所帮助。

相关问题