简体   繁体   English

如何使用 VBA 中的两个变量选择一系列单元格

[英]How to select a range of cells using two variables in VBA

I would like to use:我想使用:

    Set rng1 = .Range("A1")
    Set rng2 = .Range("C3")

as discussed in this link .如本链接所述。 The OP had cell A1 and cell C3 as two separate one-cell ranges. OP 将单元格 A1 和单元格 C3 作为两个单独的单元格范围。 He asked how to change the range so that all cells in between them are also included in a new bigger range.他询问如何更改范围,以便它们之间的所有单元格也包含在一个新的更大范围内。 My issue is similar, but my cell range changes with each new scenario.我的问题类似,但我的单元格范围会随着每个新场景而变化。 Example #1 start date in cell D1 and end date in cell Y1, new range is D1:Y1;示例 #1 单元格 D1 中的开始日期和单元格 Y1 中的结束日期,新范围是 D1:Y1; or example #2 start date in cell B1 and end date in cell AZ1, new range is B1:AZ1.或示例 #2 在单元格 B1 中的开始日期和在单元格 AZ1 中的结束日期,新范围是 B1:AZ1。 How can I change the above code so that a variable can be used instead of a static range?如何更改上面的代码,以便可以使用变量而不是静态范围?

I am not sure if I understood the question correctly.我不确定我是否正确理解了这个问题。 So, please have a look at the following and let me know if this resolves your "problem":因此,请查看以下内容,如果这能解决您的“问题”,请告诉我:

Option Explicit

Public Sub tmpTest()

Dim rng1 As Range
Dim rng2 As Range
Dim rngComposite As Range

With ThisWorkbook.Worksheets(1)
    Set rng1 = .Range("A1")
    Set rng2 = .Range("C3")
    Set rngComposite = .Range(rng1, rng2)
    Debug.Print rngComposite.Address
End With

End Sub

Essentially, the range .Range(rng1, rng2) is as dynamic as the underlying ranges and will change each time that rng1 or rng2 changes.本质上,范围.Range(rng1, rng2)与基础范围一样动态,并且每次rng1rng2更改时都会更改。

Here's a brute-force solution that builds the composite range using strings:这是一个使用字符串构建复合范围的蛮力解决方案:

rngTxt1 = Cells(Cost_Row, Cost_PnCol).Address(RowAbsolute:=False, columnabsolute:=False)
rngTxt2 = Cells(Cost_LastRow, Cost_PnCol).Address(RowAbsolute:=False, columnabsolute:=False)

Worksheets(Cost_SheetName).Range(rngTxt1 & ":" & rngTxt2).ClearFormats

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

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