Quantcast
Channel: Excel Help Forum - Excel Programming / VBA / Macros
Viewing all 49828 articles
Browse latest View live

Error Message when opening a workbook

$
0
0
Wonder if anyone has come across this.

I have a workbook with some userforms. When the workbook is loaded, it automaticlly loads a 'StartUp' userform.
StartUp form has command buttons on it that unloads the 'StartUp' form and loads whichever form has been requested.
The problem is with the 'Add Titles' form.

Sometimes this works, sometimes it doesn't. I have used the same code to load all the other forms, and in different
workbooks and have never had a problem, but for some reason, with this form, now I do.

The error message I get is ..Path/File access error. Sometimes I have to click the 'OK' button a number of times before
another message box appears - other times it appears on the first click. The second message box says....

Run-time error '75'
Could not find the specified object.

When I click the End or Debug button, excel crashes and restarts.

I have attached the workbook if anyone would care to take a look at this.

The code below is the code that is causing the problem.

Any and all help ia appreciated.

Code:


Private Sub buttAddNew_Click()

        Unload Me
        Sheets("DCPList").Select
        frmDCPLog.Show
   
End Sub

Attached Files

case sensitive string comparison

$
0
0
Hi I am using strcomp method to compare the login id provided in the userform with the login id already present in the excel sheet

I want to make this search case sensitive

if i use Login ID is ABC and the excel sheet as abc, it should not allow me to login.

If StrComp(Trim(lgtxtbxlid.Value), Trim(varlid), vbTextCompare) = 0 Then

i have even tried vbbinarycompare still it didnot work

VBA Code for more than 3 conditional formatting rules!

$
0
0
Hello Everyone, I'm a new member to this thread and forum and was hoping to obtain an answer to my question.

I have an excel sheet with wide range of numbers, Ranging 0 to 70.

I need to do the following:

1.) If numbers fall between 12 and 14, then shade the cell Red
2.) If numbers fall between 25 and 27, then shade the cell Yellow
3.) If numbers fall between 29 and 40, then shade the cell green.
.
.
.

and so forth. Both the numbers and the colors can be changed. But I'd like to add more number ranges if that is possible.

I'm a newbie to VBA, or more like clueless. I'd Really appreciate if I can get help with this problem.

All the best.
ABDULAB,

VBA to consolidate/match data within a sheet

$
0
0
Hi Guys,

I need help in creating a macro... so basically I want to match rows in (column a-g )within a sheet, once matched I want to consolidate data in columns (h-i) and move this row in sheet 2.


See the attached excel document for clarification.

Thank you for your help!


Macro_Sample_Consolidated_Data.xlsm

How to save Worksheet as separate Workbook?

$
0
0
Hi there,

I have a button on the mane page of my main spreadsheet, which will bring up a user form, in which I can select a Template (Located on another worksheet, 5 different templates) and click continue to do the rest. Now, the so called "rest" should be the way in which I can save selected template as completely separate workbook in the destination folder (without any macros in it, but with preservation of all formulas that do not reference my main spreadsheet), which I have specifically named on the settings worksheet of the main spreadsheet that is located in the same directory as the main spreadsheet. The problem is, all of my attempts to save the template ended up in great failure, because instead of saving the template I am selecting, the main page with the button, which I have mentioned above is being saved. I am ******* my hair and having 24 cup of coffee, but doing so does not help either, so please guys, help me if you can?

Thanks in advance.


Code:

  'Continue to create your invoice and check for the archive folder existance
Private Sub ContinueButton_Click()
    If cmbSheet.Value = "" Then
    MsgBox "Please select the Invoice Template from the list to continue."
    ElseIf cmbSheet.Value <> 0 Then
    Dim response
    Application.ScreenUpdating = 0
    Sheets(cmbSheet.Value).Visible = True
'Creating the directory only if it doesn't exist
    directoryPath = getDirectoryPath
    If Dir(directoryPath, vbDirectory) = "" Then
        response = MsgBox("The directory " & Settings.Range("_archiveDir").Value & " does not exist. Would you like to create it?", vbYesNo)
        If response = vbYes Then
            createDirectory directoryPath
            MsgBox "The folder has been created. " & directoryPath
           
           
           
           
            'Application.Goto Sheets(cmbSheet.Value).[a22], True
            Application.ScreenUpdating = False
        Else
            MsgBox "You need to create new folder " & Settings.Range("_archiveDir").Value & " to archive your invoices prior to creating them."
            Unload Me
        End If
        Unload Me
    ElseIf Dir(directoryPath, vbDirectory) <> directoryPath Then
       
        'Working in Excel 97-2007
    Dim FileExtStr As String
    Dim FileFormatNum As Long
    Dim Sourcewb As Workbook
    Dim Destwb As Workbook
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim fName As String
    Dim sep As String
    sep = Application.PathSeparator
   
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    Set Sourcewb = ActiveWorkbook

    'Copy the sheet to a new workbook
    ActiveSheet.Copy
    Set Destwb = ActiveWorkbook

    'Determine the Excel version and file extension/format
    TempFilePath = directoryPath & sep
    fName = Range("_newInvoice").Value
    With Destwb
        If Val(Application.Version) >= 12 Then
            FileExtStr = TempFilePath & fName & ".xlsx"
        Else
            FileExtStr = TempFilePath & fName & ".xls"
        End If
    End With

    '    'If you want to change all cells in the worksheet to values, uncomment these lines.
    '    With Destwb.Sheets(1).UsedRange
    '        .Cells.Copy
    '        .Cells.PasteSpecial xlPasteValues
    '        .Cells(1).Select
    '    End With
    '    Application.CutCopyMode = False

    'Save the new workbook and close it
       
    TempFileName = fName
    Set FileFormatNum = Workbooks.Add

    With Destwb
        .SaveAs TempFilePath & TempFileName, FileFormat:=FileFormatNum
        .Close SaveChanges:=False
    End With

    MsgBox "You can find the new file in " & TempFilePath

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
       
       
        'Application.Goto Sheets(cmbSheet.Value).[a22], True
        Application.ScreenUpdating = False
        Unload Me
    End If
    End If
End Sub

Private Sub FillInvoiceList()
Dim rngInvNumber As Range
    Set rngInvNumber = Range("Sales!A8:A1000")
    For i = 1 To 1000
        With rngInvNumber
            If .Cells(i, 1) = "" Then
                .Cells(i, 1).Value = Sheet1.Range("I11").Value
                .Cells(i, 2).Value = Sheet1.Range("I10").Value
                .Cells(i, 3).Value = Sheet1.Range("I12").Value
                .Cells(i, 4).Value = Sheet1.Range("L11").Value
                .Cells(i, 5).Value = Sheet1.Range("I49").Value
                .Cells(i, 6).Value = Sheet1.Range("I50").Value
                .Cells(i, 7).Value = Sheet1.Range("I51").Value
                .Cells(i, 8).Value = Sheet1.Range("I52").Value
                .Cells(i, 9).Value = Sheet1.Range("H23").Value
                .Cells(i, 12).Value = "1"
                Exit For
            End If
        End With
    Next i
End Sub

counter

$
0
0
Hello to all,
I am looking for a macro for this:
In F1 there is a counter.
In G1 the macro inserts the current date.
The next day in the H1 macro inserts the new date
if two dates are different G1/H1 if cell F1 is reset and the counter starts from 1.
I hope I explained.
Thanks in advance
max
-------------------------------------------------------------------------------------------
Ciao a tutti,
cerco una macro per questo:
In F1 c'è un contatore.
In G1 la macro inserisce la data odierna.
Il giorno dopo in H1 la macro inserisce la nuova data
se due date in G1/H1 se sono diverse la cella F1 si azzera e il contatore riparte da 1.
Spero di essermi spiegato.
Grazie in anticipo
max

Inherited Script for E-mailing Excel Attachments Using Gmail

$
0
0
Folks, I inherited the following script that creates and formats an excel document, then e-mails it. I'm not sure how old it is, but it takes an unusually long time to run (40-45 seconds per sheet). Since I can see the sheet being created quickly, I believe the time trap is in the e-mail section of the script. Any suggestions for streamlining that portion (bolded)?

Sub CreateAndEmailWorkbooks()
'
'
On Error GoTo Error_Handler

Dim str As String
Dim app As Excel.Application
Dim ws As Excel.Worksheet
Dim wb As Excel.Workbook
Dim row As Long
Dim vendornum As Long
Dim rslip As Excel.RoutingSlip
Dim email As String
Dim venconfn As String
Dim efname As String
Dim eraddr As String
Dim catman As String
Dim repyr As String
Dim repmon As String
Dim cmname As String
Dim intResult As Integer
Dim FilePath As String
Dim intFilesSaved As Integer
Dim intFilesEmailed As Integer
Dim strSubject As String


intResult = vbNo
FilePath = ThisWorkbook.Path & "\Reports\"
MkDir FilePath

Set app = New Application
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Vendors")

wb.Worksheets("Vendors").Activate
strSubject = wb.Worksheets("Notes").Cells(27, 7)
For row = 2 To 65000
If IsNumeric(Cells(row, 1)) = True And Cells(row, 1) <> "" Then
vendornum = Cells(row, 1)
email = ""
If Cells(row, 3) <> "" Then
email = Cells(row, 3)
email2 = Cells(row, 24)
catman = Cells(row, 21)
venconfn = Cells(row, 19)
cmname = Cells(row, 20)
efname = Cells(row, 7)
eraddr = Cells(row, 9)
repyr = Cells(row, 22)
repmon = Cells(row, 23)
End If
wb.Worksheets("Scorecard").Cells(10, 2) = vendornum
str = wb.Worksheets("Scorecard").Cells(8, 2)
Dim newBook As Workbook
Dim wks As Worksheet
Set newBook = Workbooks.Add

wb.Worksheets("Scorecard").Activate
wb.Worksheets("Scorecard").Cells.Select
wb.Worksheets("Scorecard").Cells.Copy
newBook.Worksheets("Sheet1").Activate
newBook.Worksheets("Sheet1").Cells.Select
Set wks = newBook.Worksheets("Sheet1")
wks.Paste
wks.Cells.PasteSpecial xlPasteValuesAndNumberFormats, xlPasteSpecialOperationNone, False, False
With newBook.ActiveSheet.PageSetup
.PrintTitleRows = ""
.PrintTitleColumns = "$B:$C"
End With
newBook.ActiveSheet.PageSetup.PrintArea = "$A$6:$Q$66"
With newBook.ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = ""
.RightHeader = ""
.LeftFooter = "&""Arial,Bold""PROCESS"
.CenterFooter = ""
.RightFooter = "&8Created by: SCM PDT &D" & Chr(10) & "&F"
.LeftMargin = Application.InchesToPoints(0)
.RightMargin = Application.InchesToPoints(0)
.TopMargin = Application.InchesToPoints(0.36)
.BottomMargin = Application.InchesToPoints(0.48)
.HeaderMargin = Application.InchesToPoints(0.18)
.FooterMargin = Application.InchesToPoints(0.24)
.PrintHeadings = False
.PrintGridlines = False
.PrintComments = xlPrintNoComments
.PrintQuality = 600
.CenterHorizontally = True
.CenterVertically = False
.Orientation = xlLandscape
.Draft = False
.PaperSize = xlPaperLetter
.FirstPageNumber = xlAutomatic
.Order = xlDownThenOver
.BlackAndWhite = False
.Zoom = 55
.PrintErrors = xlPrintErrorsDisplayed
End With
wks.Rows("52:54").Select
wks.Rows("52:54").Delete xlUp
wks.Rows("1:5").Select
wks.Rows("1:5").Delete xlUp
wks.Range("B8:B9").Select
With newBook
.SaveAs Filename:=FilePath & repyr & "-" & repmon & " - " & str & " - " & vendornum & ".xls", FileFormat:=xlAddIn
intFilesSaved = intFilesSaved + 1
If intResult = vbNo Then
If email <> "" Then
Set Message = CreateObject("CDO.Message")
' Make a copy of the current Excel document in the temp folder so we can add as attachment
AttachmentFile = Environ("temp") & Application.PathSeparator & ActiveWorkbook.Name
ActiveWorkbook.SaveCopyAs AttachmentFile
With Message
.Subject = "Monthly Scorecard"
.From = eraddr
.To = email
.Cc = email2
.htmlbody = "Dear " & venconfn & ", " & "<BR>" & "<BR>" & "Attached is your monthly Scorecard. If you have any questions concerning the scores, please reach out to your contact to discuss. " & "<BR>" & "<BR>" & " Best Regards, " & "<BR>" & efname
.AddAttachment (AttachmentFile) 'Add the copy as an attachemnt
With .Configuration.Fields ' Configure the remote SMTP server.
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gfs.com"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Update
End With
.send
End With
Kill AttachmentFile 'Delete the copy
End If
.Close

Set newBook = Nothing
Set wks = Nothing
End If
wb.Worksheets("Vendors").Activate
End With
End If
Next
If intResult = vbNo Then
MsgBox intFilesSaved & " Files Have Been Saved To:" & FilePath & vbLf & _
intFilesEmailed & " Files Have Been Emailed.", vbOKOnly, "Macro Results"
Else
MsgBox intFilesSaved & " Files Have Been Saved To:" & FilePath & vbLf & _
"File Delivery Via Email Disabled.", vbOKOnly, "Macro Results"
End If
Set app = Nothing
Exit Sub
Error_Handler:
Debug.Print Err.Number
Select Case Err.Number
Case 75
Resume Next
Case 1004
MsgBox "You must be connected to the company Network in order to email the Files.", vbOKOnly + vbInformation, "EMAIL ERROR"
intResult = MsgBox("Disable automatic emailing? This is recommended.", vbYesNo + vbQuestion, "DISABLE EMAILING")
Resume Next
Case Is <> 1004
MsgBox Err.Number & " " & Err.Description
End Select
End Sub

Open up a Lotus Notes Database (not mail) create a new post and attach files VBA Excel

$
0
0
Hi All,

I'm using Excel to open up a Lotus notes DB and then create a new topic and then attach a bunch of Excel files stored in a folder - I've tried many lines of code but it won't work.


Code:

Private Sub Command1_Click()
Dim session As Object
Dim db As Object
Dim doc As Object
Set session = CreateObject("Notes.NotesSession")
Set db = session.GetDatabase("", "MYLNDB.nsf")
Set doc = db.CreateDocument()
doc.Form = "Main Topic"
doc.Subject = "yo"
doc.Body = "hey"
Call doc.Save(True, False)
End Sub

I have some code which opens up the database and creates a new post but need some code for it to attach to a DB

Can you please help?

Thanks

Protect a cell

$
0
0
How to protect a single or multipal cell in excel

Vba code to run my macro in all open workbooks

$
0
0
Hi all,

I have a macro to get copy of sheet named "Doc Info" from workbook File 1
to active workbook.


i could do it for one file on any active workbook.

But what i would require is, upon executing this macro , i want this macro to get executed in all open workbooks( could be any numbers )

. i want to move copy of sheet from File 1 to all open workbooks ( which i am doing it manualy for every file )
All these open workbooks could be from any folder , wont be in same folder.

So logic is to execute my macro apply in all open workbooks in my computer.

Below is the code and i have attached file for test


HTML Code:

Sub Copysheet()
Dim wSht As Worksheet
Dim wBk As Workbook
Dim wBk1 As Workbook

Set wBk = ActiveWorkbook 'Workbooks("File 2.xls")
Set wBk1 = Workbooks("File 1.xlsm")
Set wSht = wBk1.Sheets("Doc Info")

wSht.Copy before:=wBk.Sheets(1)

End Sub

Attached Files

Program a VLOOKUP formula

$
0
0
I would like to program this formula as VBA. Is this possible? If so what would be the best way to do this? The destination cell would be Q2.

Thank you in advance!



Code:

=(VLOOKUP($B2,Bulls!$A:H,8,FALSE)*0.5)+(VLOOKUP($E2,Bulls!$A:H,8,FALSE)*0.25)

Conditional formatting using VBA

$
0
0
I am trying to get code to apply a red fill in cells in columns B:C until last cell when the date < Today & Columns D until last cell if the column does not contain an "@" symbol, I am working with excel 2003 and cannot have numerous conditional formats so I need VBA to do it, Can anyone point me in the right direction?

Vlookup data and compare variances

$
0
0
Hi

I have begun the macro coding for a stock report. The macro report has on sheet 3 the minimum stock numbers for each item which has a 5 digit stock code which I was hoping to vlookup in a weekly report to give the variances - which will in turn give an indication of which items need restocked/replenished etc and displayed on sheet 2.

Here is my code so far - can someone please please help me with how to use the v lookup on a loop ? or is there an easier way.

Code:


Sub Paul()


Application.DisplayAlerts = False
MFile = ActiveWorkbook.Name
Application.ScreenUpdating = False

WeeklyFN = Application.GetOpenFilename(fileFilter:="All files (*.*), *.*", Title:="Paul- Please open weekly stock report")
If WeeklyFN = "False" Or WeeklyFN = "" Then
    MsgBox "You have not selected a file."
    Exit Sub
Else
  Workbooks.Open Filename:=WeeklyFN
    WeeklyFN = ActiveWorkbook.Name
    MsgBox "You selected " & WeeklyFN, Title:="Paul  - GTRS File Selected"
End If

Cells.Select
    ActiveWorkbook.Worksheets("Table1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Table1").Sort.SortFields.Add Key:=Range("B2:B5000") _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Table1").Sort
        .SetRange Range("A1:E612")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Range("A1").Select
   
   
    Windows("PAULS STOCK WORKSHEET.xlsm").Activate
    Sheet2.Activate
    With Sheets(2)
    .UsedRange.ClearContents
    .Columns(1).NumberFormat = "@"
    .[a1:e1].Value = Array("stock_code", "stock_name", "minimum holding", "current stock", "variance")
    End With
    Range("A2").Select
   

End Sub
PAULS STOCK WORKSHEET.xlsmXL_Export.xlsb


The export file will be a weekly report that will be used to compare against the permanent file held on sheet 3 in "PAULS STOCK WORKSHEET.xlsm" I only want those stock items which are negative reported in sheet 2

Attachment 303931Attachment 303932

Many thanks in advance

Problems stopping chart animation with boolean

$
0
0
I am animating a chard on sheet1 with data obtained from sheet2. The chart reads cells B8:P8 on sheet 1 and these cells are updated in a for loop in my VBA code and followed by "DoEvents" so that my chart updates, this event is triggered by a button click which sets a boolean "ss" to true and starts the while loop in which the for loop sits:

Code:

Private Sub CommandButton2_Click()
ss = Not (ss)

Dim delt As Double, TotalT As Double
Dim NumberofTimeSteps As Integer, i As Integer, j As Integer

    delt = Worksheets(1).Range("H4").Offset(0, 0).Value
    TotalT = Worksheets(1).Range("I4").Offset(0, 0).Value
    NumberofTimeSteps = TotalT / delt
       
   
    Do While ss = True
        DoEvents
        For i = 1 + 1 To NumberofTimeSteps + 1
        For j = 0 To 14
        Worksheets(1).Cells(8, 2 + j).Offset(0, 0).Value = Worksheets(2).Cells(i, 2 + j).Offset(0, 0).Value
        DoEvents
        Next j
        Next i
       
    Loop
   
End Sub

The bool "ss" is declared at the start of the code using
Code:

Dim ss As Boolean
This works fine, I mean that when I press the button, the animation starts but when I press it again, it does not stop. Could someone please help me come up with a solution for stopping this.

Application.EnableCancelKey = xlDisabled can be bypassed during Workbook.Open

$
0
0
Hi there,

I have a long string of macros that have to run when a workbook is opened. There are updates happening during this process that involves opening other workbooks.

In implementing the 'Application.EnableCancelKey = xlDisabled' when holding down the ESC key while this string of macros runs, the code can be interrupted anywhere there is a workbook being opened and also when a workbook is being saved (as updates are taking place along the way).

Two workbooks are attached the demonstrate this. The code in 'Book1.xlsm' is as follows:
Code:

Sub test()

    Dim i As Long
   
    Application.EnableCancelKey = xlDisabled
   
    For i = 1 To 100000
        Cells(i, 1) = "10000"
    Next
   
    Workbooks.Open Filename:=ThisWorkbook.Path & "\Book2.xlsx"
       
    Workbooks("Book1.xlsm").Sheets("Sheet1").Activate
   
    For i = 1 To 100000
        Cells(i, 1) = "22222"
    Next

    Workbooks("Book2.xlsx").Close
   
End Sub

With the code as is, pressing and holding down the ESC key after execution will bring it to a stop at the end of the first loop where the 2nd workbook is being opened. If the line of code that opens the 2nd workbook is commented out and the same process is followed, both loops will complete even though the ESC key is pressed and held down.

Is there a way to prevent this from happening?

Thank you for any input.

TV
Book1.xlsmBook2.xlsx

Finding Min value of multiple columns in different sheets

$
0
0
Hello Everybody

My problem is that i want to calculate the min value of some cells in the same row but in different coloumns and sheets.
In the workbook I have uploaded you can see the sheet "production data". Data from that sheet is stored under the sheets: Front, Middle and Back. In the overview sheet I want to calculate Mean, min, max value of the data stored in front, middle and back. fx i need to find min value of coloumns G,I,K,M,....,BA on row 3 in the sheets front, middle and back. how is this done?

Best Regards
Attached Files

AutoFilter and Sort using VBA

$
0
0
Hi everone,

I am trying to get a small piece of my procedure to work. On the below line in red font, I receive error 438: Object doesn't support this property or method.

I am simply trying to autofilter a table, sort on the rightmost field, and then only show values > 0. The below code is a small piece of my procedure. The variable "lngLastRow" value is 1655.

Code:

With wksOutlier

    'sort by expected outlier payment and filter > $0
    .AutoFilterMode = False
    .Range("A1").AutoFilter
    With .AutoFilter.Sort.SortFields
        .Clear
        .Add Key:=.Range("A1").End(xlToRight).Resize(lngLastRow), _
            SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    End With
    With .AutoFilter.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    .Range("A1").Resize(lngLastRow, .Range("A1").End(xlToRight).Column).AutoFilter _
        .Range("A1").End(xlToRight).Column, Criteria1:=">0", Operator:=xlAnd
   
End With

I tried recording a macro, and it came up with something very similar:

Code:

    Selection.AutoFilter
    ActiveWorkbook.Worksheets("Outliers").AutoFilter.Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Outliers").AutoFilter.Sort.SortFields.Add _
        Key:=Range("BS1:BS1655"), SortOn:=xlSortOnValues, Order:=xlAscending, _
        DataOption:=xlSortTextAsNumbers
    With ActiveWorkbook.Worksheets("Outliers").AutoFilter.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    ActiveSheet.Range("$A$1:$BS$1655").AutoFilter Field:=71, Criteria1:=">0", _
        Operator:=xlAnd

Am I missing something simple? Does the worksheet need to be active?

Thanks,
Jason

Combining multiple macros into one

$
0
0
I have a userform that has the same type information on 3 different entities (name, address, phone, etc). The same research is required on each one i.e. you need to look up the zip code for each). Therefore I have a bank of buttons on each page of the multipage form. Each button does the same thing depending on which page you are on. The following is my code to copy some information and open another application depending on which page you are on and which type entity.

My question is how can I combine these into one so my module is not 3' long.

Code:

Private Sub SUMRYButton1_Click()
If Sheets("Info").Range("B197") = "BMF" Then
Sheets("Info").Range("B208").Copy
Else
End If
If Sheets("Info").Range("B197") = "IMF" Then
Sheets("Info").Range("B223").Copy
Else
End If
On Error GoTo EH
    ActivateWindow "attachmate"
    Exit Sub
EH:
    MsgBox "IDRS is not open"
End Sub
Private Sub SUMRYButton2_Click()
If Sheets("Info").Range("C197") = "BMF" Then
Sheets("Info").Range("C208").Copy
Else
End If
If Sheets("Info").Range("C197") = "IMF" Then
Sheets("Info").Range("C223").Copy
Else
End If
On Error GoTo EH
    ActivateWindow "attachmate"
    Exit Sub
EH:
    MsgBox "IDRS is not open"
End Sub
Private Sub SUMRYButton3_Click()
If Sheets("Info").Range("D197") = "BMF" Then
Sheets("Info").Range("D208").Copy
Else
End If
If Sheets("Info").Range("D197") = "IMF" Then
Sheets("Info").Range("D223").Copy
Else
End If
On Error GoTo EH
    ActivateWindow "attachmate"
    Exit Sub
EH:
    MsgBox "IDRS is not open"
End Sub

Bypass "Select Data Source" Window after SQL Query executed

$
0
0
Hello!

I have a small issue that is quite annoying and needs to be fixed.

I'm running a program that updates several sheets for performance data and this pulls from a few databases:

When I execute the code, a "Select Data Source" Window pops up with a tab that says 'File Data Source' and another saying 'Machine Data Source'.

I know the source I need; I have to click the source then "OK" several times before the code runs.

How do I bypass this?

Example Code:

Code:

With ActiveWorkbook.Connections("PRD Targets").ODBCConnection
        .BackgroundQuery = True
        .CommandText = Array( _
        "SELECT PRD06_EMPLOYEES_TARGET.dept, PRD06_EMPLOYEES_TARGET.emp_no, PRD06_EMPLOYEES_TARGET.shift, PRD06_EMPLOYEES_TA" _
        , _
        "RGET.name, PRD06_EMPLOYEES_TARGET.target" & Chr(13) & "" & Chr(10) & "FROM HIJK.dbo.PRD06_EMPLOYEES_TARGET PRD06_EMPLOYEES_TARGET" & Chr(13) & "" & Chr(10) & "WHERE (PRD06" _
        , "_EMPLOYEES_TARGET.dept In (" & dept & "))")
        .CommandType = xlCmdSql
        .Connection = _
        "ODBC;DSN=GISQL5 HIJK;UID=USERNAME;APP=2007 Microsoft Office" & _
        "system;WSID=WORKSTATION;DATABASE=HIJK;Trusted_Connection=Yes"
        .RefreshOnFileOpen = False
        .SavePassword = False
        .SourceConnectionFile = ""
        .SourceDataFile = ""
        .ServerCredentialsMethod = xlCredentialsMethodIntegrated
        .AlwaysUseConnectionFile = False
    End With

Any help would be awesome. Thanks.

IF Statment

$
0
0
I have attached a worksheet that has an If Statement on the Worksheet Tab starting in G3. I would like to program these formulas in VBA. I’m getting hung up on the fact that I am wanting to reference specific cells on the Input tab and then copy the formula down to the last cell with data.

Any help would be great.

Thank you in advance.
If Statment VBA.xlsx
Viewing all 49828 articles
Browse latest View live