如何使用VBA excel从起始单元格和结束单元格使用输入框选择范围

时间:2017-07-27 02:25:53

标签: excel excel-vba vba

我需要选择一个从例如C5开始并在P13结束的范围。

我做了一些编码,但是它有问题,我无法弄清楚。它没有合并。任何建议?

Sub Select_Range()
Dim lastrow As Long, LastCol As Long
Dim TheRow As Long, TheCol As Long
Dim StartCell As String
Dim EndCell As String
Dim startrow As Long, StartCol As Long
Dim TheRow2 As Long, TheCol2 As Long

StartCol = ActiveSheet.Cells(1, Columns.Count).End(xlToRight).Column
startrow = Cells(Rows.Count, StartCol).End(xlDown).Row
StartCell = InputBox("Enter Start cell")
TheRow2 = Range(StartCell).Row
TheCol2 = Range(StartCell).Column
ActiveSheet.Range(Cells(TheRow2, TheCol2), Cells(startrow, StartCol)).Select

LastCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
lastrow = Cells(Rows.Count, LastCol).End(xlUp).Row
EndCell = InputBox("Enter End cell")
TheRow = Range(EndCell).Row
TheCol = Range(EndCell).Column

ActiveSheet.Range(Cells(TheRow2, TheCol2), Cells(startrow, StartCol)).Select
ActiveSheet.Range(Cells(TheRow, TheCol), Cells(lastrow, LastCol)).Select

End Sub

在我选择我想要的范围后,我需要将公式插入所选范围。我如何操纵公式成为选定的范围? 这是我的公式:

ActiveCell.range.Formula = "{=MAX(($C$3:$S$20=D27)*COLUMN($C$3:$S$20))-COLUMN($C$3:$S$20)+1}"

1 个答案:

答案 0 :(得分:0)

这可能对您有帮助,

Sub PromptRangeSelection()
    Dim rng As Range
    Set rng = Application.InputBox("Select a range", "Title Here", Type:=8)
    MsgBox "The Range is " & rng.Address
End Sub

您可以通过选择并拖动鼠标或在输入框中键入范围来直接选择范围。