在我现在尝试编写的程序中,我采用两列数字并对它们进行计算。在用户告诉我之前,我不知道这两列位于哪里(他们在我的代码所在的工作簿的单元格中输入列值)。
例如,如果用户输入“A”和“B”作为所有信息所在的列,我可以根据这些值执行计算。同样,如果他们想分析另一个工作表(或工作簿)并且列位于“F”和“G”中,他们可以输入这些列。问题是我要求用户输入这两列以及其他四列(最后四列是结果列)。我这样做是希望能够使其变得灵活,但现在不灵活是可以接受的。
我的问题是,如果给我一些信息所在的值(假设为“F”),我如何找出该列在该输入值之后或之前的位置。因此,如果只给我“F”,我将能够创建一个变量来保存“G”列。
以下是我需要解决这个新问题之前变量如何工作的示例:
Dim first_Column As String
Dim second_Column As String
Dim third_Column As String
first_Column = Range("B2").Text
second_Column = Range("B3").Text
third_Column = Range("B4").Text
此处,单元格 B2 - B4 是用户输入值的位置。一般来说,我希望能够不再拥有 B3 和 B4。我觉得 Offset(0,1) 可能能够以某种方式提供帮助,但到目前为止我无法正确实现它。
谢谢你,
杰西·斯莫瑟蒙
这里有两个函数可以帮助您处理列>“Z”。它们将列的文本形式转换为列索引(作为 Long 值),反之亦然:
Function ColTextToInt(ByVal col As String) As Long
Dim c1 As String, c2 As String
col = UCase(col) 'Make sure we are dealing with "A", not with "a"
If Len(col) = 1 Then 'if "A" to "Z" is given, there is just one letter to decode
ColTextToInt = Asc(col) - Asc("A") + 1
ElseIf Len(col) = 2 Then
c1 = Left(col, 1) ' two letter columns: split to left and right letter
c2 = Right(col, 1)
' calculate the column indexes from both letters
ColTextToInt = (Asc(c1) - Asc("A") + 1) * 26 + (Asc(c2) - Asc("A") + 1)
Else
ColTextToInt = 0
End If
End Function
Function ColIntToText(ByVal col As Long) As String
Dim i1 As Long, i2 As Long
i1 = (col - 1) \ 26 ' col - 1 =i1*26+i2 : this calculates i1 and i2 from col
i2 = (col - 1) Mod 26
ColIntToText = Chr(Asc("A") + i2) ' if i1 is 0, this is the column from "A" to "Z"
If i1 > 0 Then 'in this case, i1 represents the first letter of the two-letter columns
ColIntToText = Chr(Asc("A") + i1 - 1) & ColIntToText ' add the first letter to the result
End If
End Function
现在您的问题可以轻松解决,例如
newColumn = ColIntToText(ColTextToInt(oldColumn)+1)
根据 mwolfe02 的评论进行编辑:
当然,如果您对列名称不感兴趣,而只想获取用户给定列正下方的给定行中特定单元格的范围对象,则此代码是“大材小用”。在这种情况下,一个简单的
Dim r as Range
Dim row as long, oldColumn as String
' ... init row and oldColumn here ...
Set r = mysheet.Range(oldColumn & row).Offset(0,1)
' now use r to manipulate the cell right to the original cell
会做的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)