Making Excel functions affect 'other' cells

前端 未结 6 1206
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 13:07

Let\'s say that I create a Sub (not a function) whose mission in life is to take the active cell (i.e. Selection) and set an adjacent cell to some value. This works fine.

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 13:49

    Thank you all for responding. It is possible to do this! Kinda. I say 'kinda' because technically speaking the 'function' isn't affecting the cells around it. Practically speaking, however, no user could tell the difference.

    The trick is to use a Win32 API to start a timer, and as soon as it goes off you do what you want to to whatever cell and turn off the timer.

    Now I'm not an expert on how COM threading works (although I know VBA is Single Apartment Threaded), but be careful about your Timer running away with your Excel process and crashing it. This is really not something I would suggest as a solution to every other spreadsheet.

    Just Make a Module with these contents:

    Option Explicit
    
    Declare Function SetTimer Lib "user32" (ByVal HWnd As Long, _
      ByVal IDEvent As Long, ByVal mSec As Long, _
      ByVal CallFunc As Long) As Long
    
    Declare Function KillTimer Lib "user32" (ByVal HWnd As Long, _
      ByVal timerId As Long) As Long
    
    Private timerId As Long
    
    Private wb As Workbook
    Private rangeName As String
    Private blnFinished As Boolean
    
    Public Sub RunTimer()
    
        timerId = SetTimer(0, 0, 10, AddressOf Woohoo)
    
    
    End Sub
    
    
    Public Sub Woohoo()
    
        Dim i As Integer
    
    '    For i = 0 To ThisWorkbook.Names.Count - 1
    '        ThisWorkbook.Names(i).Delete
    '    Next
    
         ThisWorkbook.Worksheets("Sheet1").Range("D8").Value = "Woohoo"
    
         KillTimer 0, timerId
    
    End Sub
    

提交回复
热议问题