【问题标题】:Range(Cells(... working incorrectlyRange(Cells(... 工作不正常
【发布时间】:2017-03-11 19:09:27
【问题描述】:

我对在 excel 中使用的 VBA 范围有一点问题:

dim frameRefPoint As String

frameRefPoint = "4,4"
range(Cells(frameRefPoint).Offset(0,0), Cells(frameRefPoint).Offset(7, 7)).Interior ...

这与我预期的不一样。我认为指定Range(Cells(4,4).Offset(0,0))中的第一个单元格应该是“D4”,但是当我在代码中使用范围时,范围的第一个单元格是“D1”~cells(1,4)。

cells(frameRefPoint) 的地址属性返回 $D$1。我在这里错过了什么?

【问题讨论】:

  • "4,4" 是字符串,不是 VBA 参数列表。
  • 您必须使用frameRefPoint = "4,4" 吗?你不能只用frameRefPoint = "D4"
  • @ShaiRado 我需要增加(向一个方向移动) - 一个表示单元格地址的变量,例如。我有 cellAdress = "C4" 我需要将它向下移动 3 行。使用细胞(4,4)更容易

标签: vba excel range


【解决方案1】:

您不能通过使用中间逗号连接值来跨越两个参数(例如 .Cells(<row>, <column>))。只是让它“看起来”像你的代码与合法代码不同。但是,您可以为每个参数使用变量。

dim r as long, c as long, frameRefPoint As string
r = 4
c = 4
cells(r, c).resize(7, 7) = "this works"

frameRefPoint = "4,4"
'split the string on the comma and convert teh text-that-looks-numbers to actual numbers
cells(int(split(frameRefPoint, ",")(0))), int(split(frameRefPoint, ",")(1)).resize(7, 7) = "this also works"

【讨论】:

  • 使用 .Resize(7, 7) 将初始单元格扩展为 7 行乘 7 列。使用.offset(0, 0).offset(7, 7) 扩展区域看起来像是乱码。
  • 我现在明白这个问题了,谢谢。我会检查 .resize 的行为方式,从来不知道它存在。
  • 其实.resize(8, 8).offset(0, 0).offset(7, 7) 是一样的。
【解决方案2】:
Range(Cells(CInt(Split(frameRefPoint, ",")(0)), CInt(Split(frameRefPoint, ",")(1))).Offset(0, 0), Cells(CInt(Split(frameRefPoint, ",")(0)), CInt(Split(frameRefPoint, ",")(1))).Offset(7, 7)).Interior....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 2019-01-09
    相关资源
    最近更新 更多