程序excel返回特定值

时间:2015-09-16 09:21:40

标签: excel vba excel-vba

我有一个将在调查中使用的电子表格。

无论调查接受者输入什么类型,如何使单元格仅返回“x”。

例如,如果我在单元格中写了“w”,它应该变成“x”。

当我保护工作簿或工作表时,我认为有一个选项。因为我可以从另一个电子表格(具有此功能)告诉它只有在工作簿受到保护时才有效。

我试图谷歌,但似乎我不知道找到答案的正确关键词。

另外,我找到了一套我操作的Vba代码,但我不确定这是否正确。我不想附上代码,因为我不想在这里混淆任何回复。

感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:1)

将此代码放在工作表模块中并测试它,当您更改A(1)列中的单元格时,它将激活,

工作表模块在哪里?

enter image description here

复制并粘贴代码,

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Count > 1 Then Exit Sub
    If Intersect(Target, Range("A1,B1,C1,A4,B4,C4")) Is Nothing Then Exit Sub
    Application.EnableEvents = 0
    If Target <> "" Then Target = "X"
    Application.EnableEvents = 1
End Sub

答案 1 :(得分:1)

这对您有用(只需将范围更改为您需要的范围):

Option Explicit
Sub worksheet_Change(ByVal Target As Range)

   On Error GoTo errorbutler 'error handler - important to have this in case your macro does a booboo
Application.Calculation = xlCalculationManual 'turn off automatic calculation to speed up the macro
Application.EnableEvents = False 'turn off events in order to prevent an endless loop
Dim LR, cell As Range 'Declare your variables
Set LR = Range("A1:b3") ' Select range of cells this macro would apply to
    For Each cell In Target 'Loops through the cells that user have changed
        If Union(cell, LR).Address = LR.Address Then 'Checks if the changed cell is part of your range
           cell.Value="x" 'changes the value of that cell to x
        End if
    Next cell

Errorexit: 'part of error handling procedure

Application.EnableEvents = True 'Turn autocalc back on
Application.Calculation = xlCalculationAutomatic 'turn events back on

Exit Sub

Errorbutler:          'error handling procedure
 Debug.Print Err.Number & vbNewLine & Err.Description
 Resume Errorexit

End Sub

哦,是的,这段代码应放入工作表模块 - 就像Dave向你展示的那样