VBA代码覆盖单元格通过用户input框移动/移动一系列单元格

我以前问过关于VBA代码的问题, 通过移动/移动一系列单元格来覆盖单元格,并得到满足我需求的答案。 然而,我意识到,我必须硬编码每个表的所有范围来执行此vbafunction,这是有风险的单元格alignment经常在表中更改。因此,我想要一个input框,允许用户select他们的单元格表想要执行这个function。我知道一个input框是如何工作的,但是给定的代码是按照行和列来进行的,而用户select的范围并不包含。 因此有没有一个input框在这个代码工作,而不必硬编码? 还是有没有其他的select,以避免在这段代码hardcording,并根据用户select的基础上工作? 所有的帮助将非常感激。

就给定的答案即兴,但我仍然得到types不匹配的错误。 为什么?

Sub Macro1() Dim y1 As Variant Dim y2 As Variant Dim x1 As Variant Dim x2 As Variant y1 = Application.InputBox("Input First Row", Type:=8) y2 = Application.InputBox("Input End Row", Type:=8) x1 = Application.InputBox("Input First Column", Type:=8) x2 = Application.InputBox("Input End Column", Type:=8) Dim sh As Worksheet Dim x As Long, y As Long Set sh = ActiveSheet ' or the specific sheet ' The 12 months For y = y1 To y2 ' Your 7 columns For x = x1 To x2 sh.Cells(y, x) = sh.Cells(y + 1, x) Next x Next y 'With sh.Cells(y2, 1) '.Select ' This only works if your column A contains dates (not strings) '.Value = DateAdd("m", 1, sh.Cells(y2 - 1, 1)) ' End With End Sub 

从最后一个问题扩展接受的答案,你可以做这样的事情:

这样用户可以使用input框来select它所作用的范围?

 Dim y1 As Variant Dim y2 As Variant Dim x1 As Variant Dim x2 As Variant Dim cell1 As Integer Dim cell2 As Integer y1 = Application.InputBox("Input First Row") If y1 = "" Or y1 = False Then GoTo handleNull y2 = Application.InputBox("Input End Row") If y2 = "" Or y2 = False Then GoTo handleNull x1 = Application.InputBox("Input First Column") If x1 = "" Or x1 = False Then GoTo handleNull x2 = Application.InputBox("Input End Column") If x2 = "" Or x2 = False Then GoTo handleNull cell1 = y2 - 1 cell2 = x1 Dim sh As Worksheet Dim x As Long, y As Long Set sh = ActiveSheet ' or the specific sheet ' The 12 months For y = y1 To y2 ' Your 7 columns For x = x1 To x2 sh.Cells(y, x) = sh.Cells(y + 1, x) Next x Next y With sh.Cells(y2, 1) .Select ' This only works if your column A contains dates (not strings) .Value = DateAdd("m", 1, sh.Cells(cell1, cell2)) End With handleNull: End 

这将在选定的范围内操作:

 Selection.Value = Selection.Offset(1,0).Value