How do I set the Focus to a Popup Dialog?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gnawoncents
    New Member
    • May 2010
    • 214

    How do I set the Focus to a Popup Dialog?

    Greetings,

    I have a datasheet, created through VBA, and I am trying to automate setting the column widths to Best Fit. Currently I loop through the controls using the code below

    Code:
        'Set width of columns to best fit data
        Dim ctl As Control
        For Each ctl In Forms![Form1].Controls
            If (ctl.ControlType = acTextBox) Then
                ctl.SetFocus
                Call TBBestFit
            End If
        Next ctl
    which calls the function TBBestFit as seen below

    Code:
    Public Function TBBestFit()
    
      On Error GoTo ErrHandler
    
      SendKeys "%B", False
      DoCmd.RunCommand acCmdColumnWidth
      Exit Function
    
    ErrHandler:
    
      Select Case Err
        Case 2046
          'Command not available
          MsgBox "Column width is not available at this time.", vbCritical, "Not Available"
        Case 2501
          'Cancel selected in dialog box - do nothing
        Case Else
          MsgBox Err.Number & ":-" & vbCrLf & Err.Description
      End Select
    
    End Function
    This works okay (does anyone know a better way?), but occasionally the popup dialog asking what width the column should be is not active when it first appears. If I click on my selection, then the subsequent iterations flow just fine. So, my question is this: is there any way in VB to set the dialog box as active so the send keys function will work properly?

    Thanks in advance for any help.
  • Lysander
    Recognized Expert Contributor
    • Apr 2007
    • 344

    #2
    Not sure, but this could be a timing issue. Try putting the command

    DoEvents

    after your ctl.setfocus and again after your sendkeys.

    This allows the computer to catch up and execute the above commands before moving on.

    Comment

    • gnawoncents
      New Member
      • May 2010
      • 214

      #3
      Thanks Lysander, this seems to have done the trick.

      Comment

      Working...