VBA excel - 使用变量选择列范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3188474/
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-11 11:50:42  来源:igfitidea点击:

VBA excel - using a variable to select a column range

excelexcel-vbavba

提问by James

VBA - The user selects a number from a combobox (1-50) and it is assigned as a variable. I now want to program a function which selects columns BA to a column to the left whatever value the user selected (I.E. from AV:BA where AV is the variable column). I have the variable the user slects as a string (dim var as string). Your help would be appreciated. Thanks

VBA - 用户从组合框 (1-50) 中选择一个数字,并将其分配为变量。我现在想编写一个函数,该函数将 BA 列选择到左侧的列,无论用户选择什么值(来自 AV:BA 的 IE,其中 AV 是变量列)。我有用户选择的变量作为字符串(dim var as string)。您的帮助将不胜感激。谢谢

回答by Ben Hoffstein

The OFFSET property is what you're looking for, although to give you a full answer it would be helpful if you posted the code you've written thus far.

OFFSET 属性是您要查找的内容,尽管为了给您一个完整的答案,如果您发布迄今为止编写的代码会有所帮助。

Here is some more info about how OFFSET works:

以下是有关 OFFSET 工作原理的更多信息:

http://www.excel-vba.com/vba-code-2-6-cells-ranges.htm

http://www.excel-vba.com/vba-code-2-6-cells-ranges.htm

Edit:Here is a quick and dirty example to get you going. In this case, the SelectColumns subroutine takes a single parameter which tells it how many columns to the left of BA should be selected (along with BA). If you execute the Test subroutine, you'll see that columns AY:BA get selected on the active worksheet.

编辑:这是一个快速而肮脏的例子,可以让你继续前进。在这种情况下,SelectColumns 子例程采用单个参数,该参数告诉它应该选择 BA 左侧的多少列(以及 BA)。如果您执行 Test 子例程,您将看到 AY:BA 列在活动工作表上被选中。

Sub SelectColumns(numColsToLeft As Integer)
    Range(Range("BA1").EntireColumn, Range("BA1").Offset(0, -numColsToLeft).EntireColumn).Select
End Sub

Sub Test()
    Call SelectColumns(2)
End Sub