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

How can I use a selected range for a ribbon macro?

$
0
0
Hello all,
I want to use a selected range as part of a onAction ribbon macro but cannot make it work. The process I am following is,
1. Select a range of cells
2. Select the ribbon action
3. Name my range as MyGph_range

Even though I selected 50 rows, MyGph_range is only showing =#REF!$J$6 as the 'Refers to' range in Name Manager. This is the portion of the code where it is happening.

Code:

Sub Mygraph(control As IRibbonControl)
Dim MyGph_range As Variant
Set MyGph_range = Selection
End Sub

Thanks for your help.

PDF--->Excel weird format result. Trying to fix with VBA

$
0
0
So I had succeeded in finally getting the pdf file converted into a semi-workable format. Some data is formatted fine, but other pages are formatted with a bunch of data input into a single cell (40-50 items). I can't get pro without my company first approving it, so I am trying to code a work-around to automate this otherwise mundane tax. New to scripting in Excel, however I did take coding classes in college. I have attached two screenshots, one with the problematic formatting, and the latter with desired formatting. The idea I have now is to have excel find instances of FP and then inserting a line-break before it. But that doesn't result in the data being in its own cell. Anyway to do this? I am reading up to try to figure it out, but if anyone can point me in the right direction, that would be great.

http://imgur.com/a/ln2uA <---- Problem Data

http://imgur.com/a/PKfMM <----- Correct Data

VBA to select a contact in outlook to Populate Contact Information in an Excel Form

$
0
0
I have a macro enabled excel form users fill out to submit new projects (or changes to projects) to our Account Unit. The form includes the contact information (Full Name, Street, City, State, ZIP; email address; office phone number and cell phone number) for our clients' Project Manager and Account's Payable Manager. The users complain about filling this information.

I am trying to find a way that the users can populate this information from their outlook accounts. The general workflow would be that the user would click a "Populate Contact" button (on the excel form) launching Outlook to their "Contacts" screen where the user could select the contact to populate the Contact Fields in the excel form.

The company subscribes to Window's 365. We are currently running 2016 versions.
I haven't been able to find something similar yet. Help would be much appreciated!

Obtain Shifts and desired Date considering given Date & Time

$
0
0
Hi Excel Experts,
I would like to prepare a summary of the attached report, where
In I column (Shift) , Requirement is Shift i.e. Day or Night
Criteria for Day : Time from 8:00 to 19:59
Criteria for Night : Time from 20:00 to 7:59
(Time is to be considered from Column H)
DATE Shift
01-07-2017 08:41 Day
01-07-2017 08:54 Day
01-07-2017 18:03 Night
01-07-2017 18:05 Night

In Column G (Date 24 Hrs), Requirement is Day for 24 Hrs.
Criteria : 24hrs Time from 1st Jul 2017 8:00 to 2nd July 7:59 and date is to be appeared in G Column as 1st Jul’2017

DATE Shift Date (24 Hrs)
01-07-2017 08:41 Day 01-07-2017
01-07-2017 08:54 Day 01-07-2017
01-07-2017 18:03 Night 01-07-2017
01-07-2017 18:05 Night 01-07-2017
02-07-2017 07:56 Night 01-07-2017
02-07-2017 07:58 Night 01-07-2017

Same calculations are to be done in Column I and G (high-lighted in Yellow in enclosed file) for all the data(dates) considering above criteria and column H.
File is enclosed for ready ref.(in the file I have done manually for 01-07-2017 and 02-07-2017)
Can anyone please help me to do it automatically.

KR
Attached Files

Macro to separate worksheet

$
0
0
I have the following macro that works great, except for one thing. I have a worksheet with Columns A through G has data and Columns H-R have a header row and a formula on line two. The Macro is creating the sheets based on data in Column A, but it is only copying the formulas for the first set of data, the rest of the sheets just have row 1 for columns H-R. I need the formulas in line two to go with the headers in line one... Attached is a sample of the worksheet I am using. I thought it might have something to do with the formulas, but it won't copy text either.



Code:

Sub Separate_ToWorksheets()
Dim lr As Long
Dim ws As Worksheet
Dim vcol, i As Integer
Dim icol As Long
Dim myarr As Variant
Dim title As String
Dim titlerow As Integer
vcol = 1
Set ws = Sheets("Sheet1")
lr = ws.Cells(ws.Rows.Count, vcol).End(xlUp).Row
title = "A1:R1"
titlerow = ws.Range(title).Cells(1).Row
icol = ws.Columns.Count
ws.Cells(1, icol) = "Unique"
For i = 2 To lr
On Error Resume Next
If ws.Cells(i, vcol) <> "" And Application.WorksheetFunction.Match(ws.Cells(i, vcol), ws.Columns(icol), 0) = 0 Then
ws.Cells(ws.Rows.Count, icol).End(xlUp).Offset(1) = ws.Cells(i, vcol)
End If
Next
myarr = Application.WorksheetFunction.Transpose(ws.Columns(icol).SpecialCells(xlCellTypeConstants))
ws.Columns(icol).Clear
For i = 2 To UBound(myarr)
ws.Range(title).AutoFilter field:=vcol, Criteria1:=myarr(i) & ""
If Not Evaluate("=ISREF('" & myarr(i) & "'!A1)") Then
Sheets.Add(after:=Worksheets(Worksheets.Count)).Name = myarr(i) & ""
Else
Sheets(myarr(i) & "").Move after:=Worksheets(Worksheets.Count)
End If
ws.Range("A" & titlerow & ":A" & lr).EntireRow.Copy Sheets(myarr(i) & "").Range("A1")
Sheets(myarr(i) & "").Columns.AutoFit
Next
ws.AutoFilterMode = False
ws.Activate
End Sub

Attached Files

Lock Cell After Data Import from an External Program

$
0
0
So i am having major grief trying to figure this out. I have data acquisition software (DASYLab) that is gathering certain data for me. I have the data programmed to dump in to an excel file from the acquisition software. Once in the excel file, it is not allowed to be edited in any way. The problem I am running across is that when running my VBA that locks the selected group of cells where the data dumps, it isnt triggered. It only triggers once the actual cell is physically selected and any info is put in the cell. Once clicked out of, the cell that was just edited is locked. I cannot figure out how to trigger the cells to lock upon data dump. Please help!
Here is my code:

1 Private Sub Worksheet_Change(ByVal Target As Range)
2 Dim xRg As Range
3 On Error Resume Next
4 Set xRg = Intersect(Range("A1:E300"), Target)
5 If xRg Is Nothing Then Exit Sub
6 Target.Worksheet.Unprotect Password:="123"
7 xRg.Locked = True
8 Target.Worksheet.Protect Password:="123"
9 End Sub

VBA coded button not working on second read only save

$
0
0
Hello

I am having a problem with my VBA button(s) on an excel program working.
This file is used by Dept A, and they "save as" their data in file name 6 digit date + customer.xlsm. Then they send it to Dept B for this input & data. Dept B saves as it with the same file name adding INV on the end (prior to the .xlsm).

Then, I open it and when I attempt to use the VBA buttons, the buttons are not "activated". My cursor is the 4-way arrows to move the button-- as if the button is inactivated.

Is there something being done incorrectly or is it just after 2 saves buttons become inactive?

Thanks in advance for the lesson.......

Repeat code on the subsequent Worksheets till there are no more

$
0
0
I have a code which works fine on my sheets but now I see that the workbooks have differing number of sheets. My last line is
Code:

range (“A1”).Select
ActiveWorkbook.Save

Now I wold like to go to sheet 2 and so the same continuing till there are no more then save the workbook. then save it all.

[B]b[/Background reasons. My code strips out what I don’t need in a bank statement as my bank do not give transactions on the transaction downloads.
Here is my code (Feel free to improve or comment). You likely don't need this. Just in case.



Code:

Sub StmtMacro()
'Use Column E to determine th rows to remain.
'Delete all others
    Columns("E:E").Select
        Selection.SpecialCells(xlCellTypeBlanks).Select
            Selection.EntireRow.Delete
   
'Now clean then up what's left
            Cells.WrapText = False
            Rows.RowHeight = 12.75
            Cells.UnMerge
            Cells.ClearFormats

'Now trim all cells
        For Each C In Intersect(ActiveSheet.UsedRange, Columns(1))
            C.Value = Trim(C)
        Next
       
'Adds consecutive numbers Create space
        Columns("A:A").Select
            Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        With ActiveSheet
            LastRow = .Range("C" & Rows.Count).End(xlUp).Row
            .Range("A2:A" & LastRow).FormulaR1C1 = "=IF(RC[1]="""","""",MAX(R1C:R[-1]C)+1)"
        End With
'Heading Col A
            Range("A1").Select
                ActiveCell.FormulaR1C1 = "Smt Nos"
            Range("A1").Select
           
' Save as is now
        ActiveWorkbook.Save
'Copy to the combined woorkbook sheet 1
        Dim NextRow As Range
       
            Range("A1").Select
                Range(Selection, Selection.End(xlToRight)).Select
                Range(Selection, Selection.End(xlDown)).Select
                    Selection.Copy
                        Windows("Combined Cleaned Transactions.xlsx").Activate
                            Range("A1").Select
                                Set NextRow = ActiveSheet.Cells(Cells.Rows.Count, 1).End(xlUp).Offset(1, 0)
                                    NextRow.PasteSpecial (xlValues)
                                        'Application.CutCopyMode = False
                                            ActiveSheet.Paste
            Range("A1").Select
                ActiveWorkbook.Save
End Sub

I hope this is an easy fix as now i am wondering why I am with such a bank. But actually I have enjoyed doing this so far. Gives me a kick.

Thanks in advance.

Mark

Run Macro If Cells=1

$
0
0
Hi All,

First of all a big thankyou to Olly, YasserKhalil, and ptmuldoon who came up with the following macro:
Code:

Sub foo()
    Dim ws As Worksheet
    Dim lRow As Long
   
    For Each ws In ThisWorkbook.Worksheets
        For lRow = 9 To 19 Step 2
            If Not IsError(ws.Cells(lRow, "AP")) Then
                If ws.Cells(lRow, "AP").Value = 1 Then ws.Cells(lRow, "O").ClearContents
            End If
        Next lRow
    Next ws
End Sub

This allows me to evaluate whether cells AP9,11,13,15,17,19 reply a "1" (derived from a formula) and then clear the corresponding cell O9,11,13,15,17,19.

However, I need this to run continuously as the worksheet is updated, not just by running the macro.

Therefore I was looking to combine it with something like:

Code:

Private Sub Worksheet_Calculate()
    If Target.Address <> "$AP$9:$AP$19" Then Exit Sub
        If Target.Value = 1 Then
            foo
    End If
End Sub

The process needs to be applied to all worksheets in the workbook, although only when active.

I'm an absolute vba novice so any help or suggestions are much appreciated and likewise if there's a different approach to acheive what I'm after that I'm unaware of.

Thankyou,

George

Exporting 7 excel columns to an Access Table using Excel VBA

$
0
0
Hello all. I' have an excel file that from a sheet DupCheck Prep,

  • I copy 7 columns (A through G) of data (of any number of rows) to,
  • an Access table tbl_InputData and then,
  • I run the access macro called Mac_RunDupCheck. I do this to check our database for records from this sheet that already exist.
  • Once complete the results show in a access table labeled as Tbl_DupCheckResults
  • The results span across 50+ columns of data which are pasted back into the excel workbook in a sheet called DupCheck Results


I'd like to automate as much as this as possible using excels VBA. I'll simplify and re-summarize this up below if anyone can help! Thanks so much!

Step 1.
Excel Export to Access
Sheet Name: DupCheck Prep
Action: Columns (A,B,C,D,E,F,G) copied to Access Table below

Step 2.
Access Import
DB Name: DupChecker 2016 v4.0
Access Table: tbl_InputData
tbl_InputData Field Columns (7): (SeqNum,InputName,InputAddress,InputAddress2,InputCity,InputState,InputZip)
(tbl_InputData can remain open or closed from view)

Step 3.
Run Access Macro
Macro Name: mac_RunDupCheck

Step 4.
Access Export to Excel
Access results table name: tbl_DupCheckResults
Export to Excel sheet name: DupCheck Results


That's it! I really appreciate any help getting as far into the steps as you can get. Thanks!!

Enter data on different sheets depending on what row is filled

$
0
0
Good afternoon,
I am after some help to make things a little easier at work.
In the attached file what I would like is if a value is entered in column C7 on the Input Sheet for example then I need the required data to be placed on both the Lost Mileage sheet and the BD / CO sheet, as this is a breakdown and needs to be recorded on both sheets
However if no value is entered in cell C7 then it is just a simple change of vehicle*and the data only needs to be recorded on the BD / CO sheet

How the sheet was set up initially is that all data was recorded on both the lost mileage sheet and the BD / CO sheet using simple grab formula (=C7, =D7...) as you will see in the file, this however caused things to get messy and caused confusion for our admin staff as mileage was being recorded as lost when it actually wasn't, it also made the sheets look very cluttered.

If that works then what I also need is if there is a time in the "From" box on the BD/CO sheet then on the Graph sheet it needs to find the corresponding graph number (ie - 1501) and enter the value on the*in the next available*cell.*
If it is a breakdown then the cell needs to be left blank with the From*time*next to it and then the replacement following on. Its a little hard to explain in writing but I hope that you can see what I mean by the examples I have placed in the sheets. Unsure if Excel can go this far to make it work though.

*
Attached Files

Debug this code

Help with ListObjects (Table3) Name manager

$
0
0
Hi All

i appear to have broken my code, doing some investigating i thing its because i don't have a defined name "Table3" in my name manager. I am not sure how to correct this, i think i lost it when i cleared the data and brought new data in. When i run the code i get the error Runtime error 9.

Code:

Sub tankloop2()

    Dim t As Integer
    Application.ScreenUpdating = False
    For t = 2 To 15
        Sheet1.ListObjects("Table3").Range.AutoFilter Field:=5, Criteria1:=Sheet1.Range("AC" & t + 1)
        With Sheets(t)
            Sheet1.Columns("A:C").SpecialCells(12).Copy .Range("A1")
            Sheet1.Columns("E").SpecialCells(12).Copy .Range("D1")
            Sheet1.Columns("P:U").SpecialCells(12).Copy .Range("E1")
          .Range(.Range("A64"), .Range("A64").End(xlDown)).EntireRow.clear
        End With
    Next t
   
    Application.ScreenUpdating = True
   
  MsgBox "Updated", vbInformation
End Sub

Moderator help

$
0
0
Can a moderator please get in touch with me, I seem to be having issues posting as well as finding a way to contact anyone for help.
I have tried the FAQ.

tnx

Need VBA Help to speed up/replace formula

$
0
0
I originally posted this problem...

"I have a spreadsheet with 2 columns. Column A contains a list of names that may or may not repeat and Column B depicting favorite colors. If a value in Column A repeats, I want to select/highlight/identify/indicate all rows where the Column B values for that name are NOT the same.

Here's the table:

Name Color
John Blue
John Blue
John Blue
Harry Yellow
Peter Red
Peter Red
Peter Blue
Peter Green

In this table, I would like to select/highlight/identify/indicate all the PETER rows."

This was under thread (https://www.excelforum.com/excel-for...-column-a.html).

Thanks to JeteMc, who worked out a conditional formatting formula for me "=COUNTIFS($A$2:$A$63000,$A2)<>COUNTIFS($A$2:$A$63000,$A2,$B$2:$B$63000,$B2)" that takes a very long time to run. If the condition is TRUE, that row would be highlighted.

The only modification I made to the formula was to use ranges "=COUNTIFS(Table1[COL1],$A2)<>COUNTIFS(Table1[COL1],$A2,Table1[COL2],$B2)". It had no effect on the speed, but it does allow for the # of rows to change without having to change the row references in the formula.

Could there be a way to use VBA to speed up the conditional formatting? I cannot post the file due to client confidentiality issues, but the example file in the original link is attached.

Thanks in advance for your help!

VBA help for a complete beginner - Copy and pasting from Excel to Word template

$
0
0
Hello Everyone

I am a complete novice at VBA having only picked it up a day or two ago with no previous programming experience. Here's my problem if anyone out here is able to help:

I have created an excel document that can be used to populate a table on one of the worksheets (Switching Sequence) using a number of different drop down boxes. The choices made on the drop down boxes are shown in another table on another worksheet (Populated Table). This table on "Populated Table" needs to be copied and pasted into an existing template where it can be saved and printed off for use.

The table consists of the following rows:

Operation Number (column B) , Location (column C), Circuit or Device (column D), Operation (column E), Complete? (column F), Date and Time (column G)

Is there a way in which my code is able to copy the table (range B5:G82) and then only past the rows in which there is an Operation in its corresponding D cell?

Here is what I have already. So far it copies and pastes the whole range (B5:G82) but I am unable to make it ignore the rows with a blank in it's corresponding D column.

Sub CopyToWord()
Dim wd
Dim Data As Range
Dim Doc



Set Data = Sheets("Populated Table").Range("B5:G82")
Data.Copy
Set wd = CreateObject("Word.Application")
wd.Visible = True
Set Doc = wd.Documents.Add(Template:="C:\Users\user\Documents\Work\Switching Program\test2.docx")
wd.Selection.Paste

Application.CutCopyMode = False

End Sub

I will attach my excel sheet so if anyone has chance they can have a proper look at it.

So in summary I want to be able to:

1. Populate table in Excel
2. Copy table
3. Paste table in word template but without the rows with a blank cell in its D column


Any help would be amazing

Many thanks

AM2809
Attached Files

Collate data from different sources

$
0
0
Hi Guys

I have a work sheet that has data from 2 different sources for the same thing and I am looking for a macro to try and collate the error quantity and head waste data so I can compare them. any help appreciated, thanks for looking
Attached Files

need code to add table to activecell current region

$
0
0
need code to add table to activecell current region

can any body help me in this ??? :)

insert new row:copy above formulas and formatting

$
0
0
I am trying to insert a new row into my excel sheet but I want the formulas to be copied from the above row...is there a way to do this? I currently have the following code to insert rows above named ranges:

Code:

Sub TextBox8_Click()
With Sheets("XBA")
    .Unprotect Password:="PW"
If Range("a") = True Then

Range("GcNewRow").Insert Shift:=xlDown, _
      CopyOrigin:=xlFormatFromAbove
End If
    .Protect Password="PW"
End Sub

any help is appreciated....I have been fiddling with this all day to no avail.

Looping macro to save active sheet as PDF with specific name

$
0
0
Hi,

I'm trying to get my looping macro to save as PDF using a specific cell (which changes every loop) as naming convention. The loop pulls data in from the "Master" tab. I want the name to save as cell "G3" on the main sheet. I can't figure out why it isn't working... can anyone help?

Code:

Sub Schedule_To_PDF()

    '/define initial vars/'
    Dim w As Worksheet
    Dim start As Integer
    Dim last As Integer
    Dim counter As Integer
    Dim filename As String

    '/define range/'
    start = ActiveWorkbook.Worksheets("Master").Range("B1").Value
    last = ActiveWorkbook.Worksheets("Master").Range("B2").Value

    '/stop screen update/'
    Application.ScreenUpdating = False
   
    '/create loop by performing the following:
    '/activate Fee Schedule, set start value, "print out" values, export file ONLY if Fee
    '/Schedule desired, increment count of start, and repeat for next value in range
    For counter = start To last
        Set w = ActiveWorkbook.Worksheets(1)
        Worksheets("Master").Range("B4") = start
        w.PrintOut
       
        If Range("G4").Value = "Yes" Then
            w.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
                Range("G3").Value, Quality:= _
                xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
                OpenAfterPublish:=False
        End If
       
        start = start + 1
       
    Next counter
   
    '/resume screen update/'
    Application.ScreenUpdating = True
   
End Sub

Viewing all 50110 articles
Browse latest View live