2016-07-09 7 views
-6

行と列のテキストが一致したときにユーザーがその値を入力できます。それ以外の場合、ユーザーは値を入力することはできません。残りのセルは、0またはヌル値を示すことができます。私はVBAでそれをやりたいと画像は参考用ワークシートのコードペインで行と列のヘッダーが一致する場合にのみセルの値を入力します

enter image description here

+4

このサイトは、特定のコード関連の質問であり、「コードは無料」ではありません。 [How to ask](http://stackoverflow.com/help/how-to-ask)を参照し、それに従って質問を変更してください。 –

+0

シート内のすべてのセルをロックし、列ラベルが行ラベルと同じセルをロック解除し、シートを保護します。コードを試してみたら、それを見るのがよいでしょう。 –

答えて

1

ところ、このコードは次のとおりです。

Private Sub Worksheet_Change(ByVal Target As Range) 
    If Target.Value <> "" Then '<--| bother only when user inputs values, not when he/she deletes them 
     If Cells(2, Target.Column) <> Cells(Target.Row, 1) Then '<--| if edited cell row (row 2) and column (column 1) headers don't match then ... 
      MsgBox "Sorry you must input a cell whose row and column headers match !" '<--|... inform the user... 
      Application.EnableEvents = False ' <--|... disable events not to have this event handler be called in an infinite loop,,, 
      Target.ClearContents '<--| clear the invalid userinput 
      Application.EnableEvents = True '<--| enable back events and have them run for subsequent user inputs 
     End If 
    End If 
End Sub 
0

代替方法、場所、ユーザーのすべてのセルをロックすることで、エントリを防ぎますデータを入力することはできません。

Sub StopEntries() 

Dim ws As Worksheet 
Dim wb As Workbook 
Dim SheetRow As Integer 
Dim SheetColumn As Integer 
Const ColumnHeaderRow As Integer = 2 
Const RowHeaderColumn As Integer = 1 
Const NumberOfRows As Integer = 21 
Const NumberOfColumns As Integer = 21 

Set wb = Workbooks("TestBook.xlsx") 
Set ws = wb.Worksheets("LockedSheet") 

With ws 
' lock all cells 
ws.Cells.Locked = True 

' unlock cells that meet the condition 
For SheetRow = 1 To NumberOfRows 
    For SheetColumn = 1 To NumberOfColumns 
     If .Cells(SheetRow + ColumnHeaderRow, RowHeaderColumn) = .Cells(ColumnHeaderRow, SheetColumn + RowHeaderColumn) Then .Cells(SheetRow + ColumnHeaderRow, SheetColumn + RowHeaderColumn).Locked = False 
    Next SheetColumn 
Next SheetRow 

' protect the sheet 
.Protect UserInterfaceOnly:=True 
End With 

End Sub 
関連する問題