2015-09-16 118 views
2

我以前問過關於VBA code to overwrite cells through moving /shifting up a range of cells的問題,我得到了滿足我需求的答案。然而,我意識到我必須硬編碼每個表的所有範圍來執行此vba功能,這是有風險的,因爲單元格對齊經常在表單中變化。因此,我想要一個輸入框,允許用戶選擇他們的單元格表想要執行這個功能。我知道輸入框是如何工作的,但是給定的代碼按行和列排列,用戶選擇的範圍不包含。因此,有沒有辦法使輸入框在此代碼中工作而不必硬編碼?還是有沒有其他的選擇,以避免這段代碼硬編碼,並根據用戶的選擇基礎工作?所有的幫助將非常感謝。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 

回答

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 
+0

我得到一個類型不匹配錯誤。 – Niva

+0

仍然是相同的錯誤:/ – Niva

+0

我在這條線上得到錯誤。 'cell1 = y2 - 1' – Niva

1

這將在選定的範圍內運行:

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

但我如何把這個。如只在一個輸入框中會做或? – Niva

+0

使用可以先選擇範圍,然後運行宏。 –

+0

這非常容易!感謝噸! – Niva

相關問題