2016-04-18 32 views
1

我正在尝试编写一个允许用户输入新的钞票序列号的宏。该宏需要3个输入(货币,面额和序列号)。我是VBA的初学者,但我试图写的代码如下。任何人都可以指出我错在哪里,或者需要改变什么才能使它工作?谢谢!在VBA中定义单元格

Sub TestSub() 
Dim Note_Serial As Variant 
Dim Note_Currency As Variant 
Dim Note_Denomination As Variant 
'Defining 3 inputs 

Note_Currency = InputBox("Enter Currency (in 3 letter form):") 
Note_Denomination = InputBox("Enter Note Denomination (with $ sign):") 
Note_Serial = InputBox("Enter Serial Number:") 
'Getting 3 inputs 

Dim Currency_Cell As Range 
Dim Denomination_Cell As Range 
Dim Serial_Cell As Range 
'Defining cells to write inputs 

Currency_Cell = (D3) 
Denomination_Cell = (E3) 
Serial_Cell = (F3) 
'Starting cells 

Currency_Cell = Note_Currency 
Denomination_Cell = Note_Denomination 
Serial_Cell = Note_Serial 
'Writing inputs to spreadsheet 

Currency_Cell.Offset (1) 
Denomination_Cell.Offset (1) 
Serial_Cell.Offset (1) 
'Moving all cells down 1 place 
End Sub 

回答

2

而是写作Currency_Cell = (D3),你想写Set Currency_Cell = Range("D3")(假设你不切换活动工作表)。

编辑:为了避免覆盖先前输入的数据,使用来代替:

Set Currency_Cell = Cells(Rows.Count, Range("D3").Column).End(xlUp).Offset(1, 0) 

这将在列中的第一个空白单元D.

要移动单元格引用,你也必须使用Set关键字,并给出行和列的偏移量:

Set Currency_Cell = Currency_Cell.Offset (1, 0) 
+0

谢谢!输入现在工作并写入正确的单元格。但是,当我输入第二个音符时,它会覆盖第一个音符。你能解释为什么会发生这种情况吗?再次感谢 – 1937827

+0

这是因为你总是从第3行开始,覆盖以前写入的数据。我更新了我的答案以防止这种情况发生。 – Verzweifler