質問

if I programmatically or manually enter a value, let's say 10000, into an excel cell, I need it automatically divided it by 1000 for me, can this happen?

No.1, I am not asking about display format, I need seriously change the entered value.

No.2, the formula shall not apply to the whole worksheet.

役に立ちましたか?

解決

You can do this by using the Worksheet change event. However to make sure that you only do this once and not everytime this event is fired, you need to track the value somewhere. You can do this on an invisible sheet, somewhere else on the sheet, etc.

Logic wise, you basically check when a cell is changed if it's in the range of cels you want this to happen. If it is, you make sure that it's not the same value it had before you touched the cell (no changes were made) by comapring it to the record. If it has changed, you simply divide by 1000 and update the record.

Hope this helps.

Private Sub Worksheet_Change(ByVal Target As Range)

'Turn off events to stop this from looping
Application.EnableEvents = False

'Let's say you want this to happen for A1:A10
'Store the value of the cells on a hidden sheet or somewhere. Here let's assume B1:B10 is the hidden record

If Target.Column = 1 Then
    If Target.Row > 0 And Target.Row < 11 Then
        If Target.Value <> Target.Offset(, 1) Then
            Target.Value = Target.Value / 1000
            Target.Offset(, 1).Value = Target.Value
        End If
    End If
End If

'Turn events back on
Application.EnableEvents = True

End Sub

Sorry for some reason the formating thing is not indenting the code properly...

他のヒント

I'd shy away from this if I were you as you'll get problems with reediting the cell with perpetual dividing by 1000. Of course you could multiply the number by 1000 when editing starts but I don't see that being particularly robust.

The approach I would take would be to have a region of the spreadsheet (that the user doesn't normally see) that contains formulas of the form =A1/1000 and have the rest of the calculation flow depend on those cells.

Doing this means you keep everything on-spreadsheet with no VBA.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top