有没有一种快速的方法可以从 VBA 的范围中获取列字母?

时间:2021-02-10 20:53:24

标签: excel vba

正如您在以下代码中所见,我创建要复制的特定范围的方法非常广泛。有没有更有效的方法?

    For counter = 1 To quantity
    
        Set header_range(counter) = _
        Application.InputBox("Select the HEADER of the " & counter & "º column you want to copy", Type:=8)
        
        col_number = header_range(counter).Column
        last_row = Cells(Rows.Count, col_number).End(xlUp).Row
        col_letter = Split(Cells(1, col_number).Address(True, False), "$")(0)

        Range(header_range(counter), Range(col_letter & last_row)).Copy
        
        target_wb.Sheets("Sheet1").Cells(1, counter).PasteSpecial
        
    Next counter

1 个答案:

答案 0 :(得分:3)

您不需要使用实际的字母。相反,将列和行索引与 Cells 对象一起使用。 Cells 输入是索引 Cells(Row Index, Column Index)。我还建议使用较短的变量名称以提高可读性

  • r = 行索引
  • c = 列索引

以下是使用索引复制通过 Row 1 选择的变量列中从 rInputBox最后一行)的范围的示例

Sub Example()

Dim Input_C As Range
Dim r As Long, c As Long

Set Input_C = Application.InputBox("Select Target Header", Type:=8)

'Convert to Index
c = Input_C.Column
r = Cells(Rows.Count, c).End(xlUp).Row

'Build Dynamic Range
Range(Cells(1, c), Cells(r, c)).Copy

End Sub
相关问题