使用用户输入框

时间:2015-09-16 02:13:25

标签: excel vba excel-vba inputbox

我之前在VBA code to overwrite cells through moving /shifting up a range of cells上问过一个问题,我得到的答案符合我的需要。然而,我意识到我必须硬编码每个表的所有范围来执行这个vba函数,这是有风险的,因为单元格对齐经常在工作表中更改。因此,我想要一个允许用户选择单元格表的输入框想要执行这个功能。我知道输入框是如何工作的,但是给定的代码按行和列排列,用户选择的范围不包含。因此,无论如何输入框都可以在此代码中工作而无需硬编码?或者是否有其他替代方法可以避免在此代码中使用硬编码并使其基于用户选择基础工作?非常感谢您的所有帮助。

在给定答案上即兴创作,但我仍然遇到类型不匹配错误。为什么会这样?

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

2 个答案:

答案 0 :(得分:1)

从上一个问题中扩展接受的答案,你可以这样做:

那样用户可以使用输入框选择它所作用的范围吗?

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

答案 1 :(得分:1)

这将在所选范围内运行:

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