简体   繁体   English

如何根据 VBA 中的两个变量获取范围

[英]How to get range based on two variables in VBA

I have a last_row and last_column variable.我有一个 last_row 和 last_column 变量。

I get these by doing the following.我通过执行以下操作得到这些。

last_column =.Cells(1, .Columns.Count).End(xlToLeft).Column

and

last_row =.Range("A" &.Rows.Count).End(xlUp).Row

My question is this, I'm trying to create a selection based on these variables, so that the range goes from E33 to the last row and column.我的问题是,我正在尝试根据这些变量创建一个选择,以便范围从E33到最后一行和最后一列。 However, I am getting an error.但是,我收到一个错误。 Here is the code.这是代码。

Range("E33:" & last_column & last_row).Select

Thanks so much for your help!非常感谢你的帮助!

You can use Cells() with column and row numbers您可以将 Cells() 与列号和行号一起使用

set myRange = Range(Cells(33, "E"),Cells(last_row,last_column))

Unless you're using this code in a sheet module, make sure you qualify the sheet that the Range and the Cells method address.除非您在工作表模块中使用此代码,否则请确保您限定了 Range 和 Cells 方法所寻址的工作表。

Range("E33:" & last_column & last_row).Select范围("E33:" & last_column & last_row).Select

You need to convert the last_column to a string before you use it in the above code.在上面的代码中使用它之前,您需要将last_column转换为字符串。 Is this what you are trying to achieve?这是你想要达到的目标吗?

Dim ColName As String
Dim rng As Range

ColName = Split(Cells(, last_column).Address, "$")(1)
Set rng = ws.Range("E33:" & ColName & last_row)

In the above code ws is the relevant sheet.在上面的代码中, ws是相关的工作表。

NOTE笔记

  1. Avoid the use of .Select .避免使用.Select You may want to see How to avoid using Select in Excel VBA您可能想查看如何避免在 Excel VBA 中使用 Select
  2. Excel column number from column name Excel 来自列名的列号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM