我正在为Excel表单编写VB代码,提示用户回答一系列问题,然后将响应按行存储在工作表上。目前,代码在A2中存储第一个响应,然后在B2中存储第二个响应,依此类推。当屏幕上出现感谢提示时,子结束。
我想做的是当所有问题都被回答时,光标将移动到下一行的第一个单元格(A3),以便为另一个人存储相同问题的答案。它必须继续前进到下一行。
这些是代码的主要部分
Sub dform ()
Dim mName As String
mName = InputBox("What is your maiden named", "Maiden Name")
Range("A2").Select
ActiveCell.FormulaR1C1 = mName
x = MsgBox("Are you still married?", 4)
If x = 6 Then Range("G2").Value = "Yes"
If x = 7 Then Range("G2").Value = "No"
Exit Sub
End Sub
答案 0 :(得分:1)
首先,您可能想要编辑您的问题,因为这些问题要求非常不同:
What is your maiden named
What is your maiden name?
我对您的代码进行了一些修改。评论应该有助于您了解正在发生的事情。使用此方法,您可以在不必选择或显示包含所有答案的工作表的情况下提出问题。
我用一个设置为ws
对象A列中第一个空行的变量替换了您的硬编码行。您可以将ws
设置为您的工作表调用的任何内容。现在,您可以根据需要多次运行它,并始终将新答案附加到新行。
' use this statement at the top of all modules to require variable declaration
Option Explicit
Sub dform()
' declare your variables
Dim wb As Workbook
Dim ws As Worksheet
Dim firstEmptyRow As Long
Dim mName As String
Dim x As Long
' you need the "set" keyword for object variables
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
' the best way to get the last row is to go up from the bottom of the sheet
' add 1 to get the first empty row
firstEmptyRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row + 1
mName = InputBox("What is your maiden named", "Maiden Name")
' always avoid selecting or activating in VBA code
ws.Range("A" & firstEmptyRow).Value = mName
x = MsgBox("Are you still married?", 4)
If x = 6 Then ws.Range("G" & firstEmptyRow).Value = "Yes"
If x = 7 Then ws.Range("G" & firstEmptyRow).Value = "No"
Exit Sub
End Sub
答案 1 :(得分:0)
您可以尝试在循环中使用Cells或Offset属性:
http://msdn.microsoft.com/en-us/library/office/aa139976(v=office.10).aspx
答案 2 :(得分:-1)
两种可能的解决方案是:
我认为第一种方法是最简单的方法,而且它是持久的(保存书籍时会存储行号)。
因此,我们假设您有一张名为utilitySheet
的工作表,并存储了单元格B2
中使用的最后一行。当然,该值必须是整数。
所以你可以这样:
sub dform()
dim mName as String
dim nRow as Integer
nRow = ThisWorkbook.Sheets("utilitySheet").Cells(2,2).Value
' ...
If x = 6 then ThisWorkbook.Sheets("results").Cells(nRow + 1, 7).Value = "Yes"
If x = 7 then ThisWorkbook.Sheets("results").Cells(nRow + 1, 7).Value = "No"
' ...
' Update the row number in the utility sheet
ThisWorkbook.Sheets("utilitySheet").Cells(2,2).Value = nRow + 1
end sub