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

Copy comment on same column in new rows on dynamic table?

$
0
0
I searched in some places for this code (and use search in this forum) but I didn't see anything related. Just want to copy the comment of first row on a dynamic table to every new cell in that column generated.

Thanks for your time.
Attached Files

[SOLVED] Print button that still prints when cancelled at the printer setup window

$
0
0
Hello.
I'm trying to set a print button that when pressed, it will show up the available printers and then print out a specific range of cells in a specific number of copies. I've tried the following code.

Code:

Private Sub Print1_Click()
Application.Dialogs(xlDialogPrinterSetup).Show
Set MyRange = Range("B1:E5")
iNumCopies = Range("J1").Value
If iNumCopies < 1 Then iNumCopies = 1
MyRange.PrintOut Copies:=iNumCopies
End Sub

It works well with printing but if I press cancel on the printer setup dialog, it still prints. How could I add a code to prevent this?
Thank you.

Help with Mail Merge Auto Email VBA - Multiple CCs.

$
0
0
Hi,
I have an excel macro / spreadsheet that i use to mass emailing people. It has been re-purposed over the years for various functions, so, to be honest, there is lots of stuff in it that probably is not relevant to what I need now. I'm not the creator, though I've had to make some tweaks over the years.. but, i'm not a programmer.

So, the script will take data from the tab "RFCs Not Closed", compile unique spreadsheets for each name in Column F, then create the email, attach the spreadsheet with the rows of data matching on Column F.
So, in the attached example, I will get 1 email, addressed to jacob two-two, it will have a spreadsheet with the columns/rows of data that you can see on the first tab. It will email the email address in Column G.

What I'm trying to do, is get it to CC the names in Column I, for every row of data. Right now, it will CC the first name it comes across "per name" in Column F. So, if I have 5 managers... I'll get 5 spreadsheets, with 5 emails. If a manager has say 10 rows of data, even if the CC name has 10 unique names for that manager, it will pick only the first one, and CC it. Hopefully this is making sense what I'm saying.

Essentially, i want rows of data for the manager, and for it to CC all the users as well so they are aware the manager is being emailed (its for following up with outstanding training).
I've attached the file (or hopefully I've attached it!)

Can anyone help? Is this possible to do without having to re-write the whole script? The coding is on the object "sheet1 (RFCs Not Closed)". I'm sorry if this is a bit too much info provided, but I'm just not sure which function that needs to be modified.

Rilly
Attached Files

Locking / Unlocking Cells

$
0
0
Hello, Hope someone can help.

I have a sheet that needs to have cells locked or unlocked according to if then

I have about 400 rows that can have data entered in, each row has 9 columns that can have data entered in, but I only want them to be able to enter in data on conditions.

Starting with row 5
IF B5 = 1 then
Clear cells C5, E5,
Lock Cells C5, E5
Unlock Cells G5
else if B5 = 3 Then
Clear Cells G5
Lock Cells G5
Unlock Cells C5, E5
Else If B5 = 4 Then
Clear Cells E5, G5
Lock Cells E5, G5
Unlock Cells C5
Else
Clear Cells C5, E5, G5, H5, I5, J5, K5, L5
Lock Cells C5, E5, G5, H5, I5, J5, K5, L5
end if

And I would need this for all 400 rows (row 5 through 405)

Also Need to unlock or lock the next row based on column J having a value entered.

IF J5 <> "" then
Unlock B6
end if


Hope that all makes sense. Thanks for your help on this.

Broken Code. Web Data Pull

$
0
0
I had some code that was working fine for weeks and all of a sudden it no longer works anymore. I'm still a novice at vba. Do any of you have an idea as to why this might happen.

here is the code:
Code:

Sub Five_Year()

 
Sheets("Raw5").Cells.ClearContents

    Dim Stock As String
    Dim xConnect As Object

   
    ST = Sheets("Grading Sheet").Range("B2") ' ticker symbol of stock
    SD = (Sheets("Grading Sheet").Range("C11") - DateValue("January 1, 1970")) * 86400 'today - 365*5
    ED = (Sheets("Grading Sheet").Range("C12") - DateValue("January 1, 1970")) * 86400 'todays date

    'Retrieve 5 Yr Data
    With Sheets("Raw5").QueryTables.Add(Connection:= _
    "finance.yahoo.com/quote/" & ST & "/history?period1=" & SD & "&period2=" & ED & "&interval=1mo&filter=history&frequency=1wk" _  'ignore faulty link
    , Destination:=Sheets("Raw5").Range("$A$1"))

        .Name = "5Yr"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .WebSelectionType = xlEntirePage
        .WebFormatting = xlWebFormattingNone
        .WebPreFormattedTextToColumns = True
        .WebConsecutiveDelimitersAsOne = True
        .WebSingleBlockTextImport = False
        .WebDisableDateRecognition = False
        .WebDisableRedirections = False
        .Refresh BackgroundQuery:=False
    End With
   
    End Sub

Attached Files

select and sum the values for specific ID

$
0
0
Hi I'm trying to sum a specific values for each user ID in same ID_shop, the user IDs are (81 to 86)

my code is not complete:

Code:

Private Sub deletecancel_Click()
    Dim myRange As Range
  'declare object variable used to iterate through the elements of the cell range
    Dim iCell As Range
    'declare variable to hold value you search for
    Dim myValue As Integer
    Dim myValue1 As Integer
    Dim myValue2 As Integer
    Dim myValue3 As Integer
    Dim myValue4 As Integer
    Dim Lastrow5 As Integer
    LastRow = Cells(Rows.Count, "B").End(xlUp).Row
    Set myRange = Range("B2:B" & LastRow)
    'set value  to search for
    myValue = 81
    myValue1 = 82
    myValue2 = 83
    myValue3 = 84
    myValue4 = 85
    myValue5 = 86
    'loop through each cell (iCell) of the cell range (myRange)
    Application.EnableEvents = False
    For Each iCell In myRange
        'test if value i. If condition is met, clear cell
        If iCell.Value = myValue Or iCell.Value = myValue2 Or iCell.Value = myValue3 Or iCell.Value = myValue4 Or iCell.Value = myValue5 Then
        iCell.Offset(, 3).Value = ..
        End If
    Next iCell
    Application.EnableEvents = True
End Sub

How can I select the values in column C for this users ID and sum them and put the result in the end of ID_shop?
the first sheet is my example of my data and the second is the result that I need
Attached Files

saving file with new named folder

$
0
0
Hello I am trying this code and cannot seem to get the file to save

I want to create a new folder each time named by the fields in the userform

Code:


MKDir Location
Set Location = "& Me.TxtTNo & " & " & Me.txtcustname.Value & " & " & Me.txtoptsurfacesn & "

nwb.SaveAs Filename:="C:\Users\Chris' Laptop\Desktop\Location\" & Me.TxtTNo & " " & Me.txtcustname.Value & " " & Me.txtbbsn & " " & Me.txtoptsurfacesn & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled

Any help much appreciated

Cannot delete a worksheet when a change event for a userform combobox detects rename sheet

$
0
0
In the attached workbook, there is a modeless userform which has a combox with a rowsource pointing to the first worksheet "Sheet1!$B$1:$B$2".

I have added a change procedure (event) to the combox, so that if a combox value changes, this will be triggered and the second worksheet will be deleted.

What is good about this event, is that when you rename/delete any worksheet inside the workbook this event will be triggered. However, in this case, I am getting the following errors when it wants to delete the second worksheet:

Run-time error '1004':
Delete method of Worksheet class failed

When I press End button on the error message, the following error is thrown:
---------------------------
Microsoft Visual C++ Runtime Library
---------------------------
Runtime Error!

Program: C:\Program Files\Microsoft Office\Office14\EXCEL.EXE

R6025

- pure virtual function call

Any help to resolve this issue is appreciated. The code is also given below:

Code:

'ThisWorkbook
Private Sub Workbook_Open()
    UserForm1.Show (vbModeless)
End Sub

Code:

'UserForm1
Dim EnableEvents As Boolean

Private Sub ComboBox1_Change()
    If EnableEvents Then
        MsgBox "Running change event", vbInformation, "Test"
        givenVal = ComboBox1.Value
        EnableEvents = False
        MsgBox "Trying to delete the second worksheet", vbInformation, "Test"
        ThisWorkbook.Worksheets(2).Delete
        EnableEvents = True
    End If
End Sub

Private Sub UserForm_Initialize()
    EnableEvents = False
    UserForm1.ComboBox1.RowSource = "[TestComboBox.xlsm]Sheet1!$B$1:$B$4"
    UserForm1.ComboBox1.ListIndex = 3
    EnableEvents = True
End Sub

Attached Files

Random drawing (Randomizer) with maximo of numbers that the result can apper

$
0
0
Hello Guys, please help me, all ideas are welcome.


I need to send randomly some specific task to people, (like an automatic drawing) I have the list of the Tasks and I have the % saying how many people can be assigned to do the same thing on the day I chose.

Any ideas, Please?:)
Attached Files

[SOLVED] Help editing VBA code that uses MySQL queries to show also column names

$
0
0
Dear all,

I'm using one old excel file with a VBA code that allows to do MySQL queries on other excel files.

The file works great, but whenever I do queries, the pasted data does not contain the column names, which I would like to have. Can someone help me out on editing this code to whenever I do queries I get also the column names please?

Here is the code that I'm using, and I will also attach the file and one example database file too.

MODULE:
Code:

Option Explicit
'Criação das variáveis globais para utilização em todos os módulos
Global str_Conexao 'As String
Global ado_Conexao 'As ADODB.Connection
Global str_Versao 'As String


Sub Conectar_Excel()
 
    Dim Caminho As String
    Dim Arquivo As String
   
    Caminho = Planilha2.Range("c4")
    Arquivo = Planilha2.Range("c6")
   
    'Define string de Conexão
    str_Conexao = _
        "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" & _
                "DSN=TESTE_SQL;DBQ=" & Caminho & Arquivo & ";" _
                & "ReadOnly=0;DefaultDir=" & Caminho & ";" _
                & "DriverId=1046;FIL=excel 12.0;MaxBufferSize=2048;PageTimeout=5;"
   
    'Seta ADODB
    Set ado_Conexao = CreateObject("ADODB.Connection")
   
    'Abre Conexão
    ado_Conexao.Open str_Conexao
   
   
End Sub

WORKSHEET
Code:


Private Sub CommandButton1_Click()

listar_dados

End Sub


Sub listar_dados()
 
 
  'Chama rotina de Conexão
  Call Conectar_Excel
                 
  'Seta RecordSet
  Set rs_Consulta = CreateObject("ADODB.Recordset")

  'Define da Query
  str_consulta = Planilha1.Range("G5")
                             
  'Abre Recordset
  rs_Consulta.Open str_consulta, ado_Conexao
   
  'Limpa o Relatório
  limpar
   
  'Cola Recordset na planilha
  Planilha1.Range("b13").CopyFromRecordset rs_Consulta
         
  'FechaConexão
  rs_Consulta.Close
  Set rs_Consulta = Nothing
             
End Sub

Sub limpar()

Planilha1.Range("b12:aa5000").ClearContents

End Sub

Thank you all for any help!
Attached Files

Finding 5 largest values in a column and then returning the rows that correspond

$
0
0
Hi,

I have a macro where i need to identify the 5 largest values in a specific column of data. Note: Lets say there are 30 columns of data in this file.
I need to copy and paste the rows which correspond to these 5 largest values into another worksheet. I am not sure the best way to do this. I was thinking of using "FIlters" but i am not sure how yet.

Any thoughts on how to approach this?

Fast count of integer's divisors

$
0
0
I am looking for a fast way to count the number of divisors of a 9-digit number using VBA.

I can find the count using this function:

Code:

Public Function tau(n As Double) As Double

Dim k As Double

tau = 0

For k = 1 To n

If n Mod k = 0 Then tau = tau + 1

Next k

End Function



But it is far too slow. Is there a faster way?

Workbook_open event, or rather non-event!

$
0
0
So this is a long running issue for me, on and off. I have a stack of spreadsheets that have workbook_open events to do a number of things. So today one of them decided not to do anything on opening. I stripped the code and selected a new Workbook_Open event from the VBE dropdown boxes and just put a message box in it. It refused to run...

After a bit of research there is some question over whether conditional formatting interferes with it. So I stripped this off the front page and saved it as a different name. On opening it ran, so thought I had sorted it. I went to show someone it and it didn't work (barely moments after it had). SO went to open the original (with the conditional formatting). Lo and behold it worked!!

So after some back and forth it seems that if I open Excel and open a workbook (either one) the code won't run. But if I then open the other one it does! I have run application.enableevents=true a spectacular number of times but no difference to the result. And it is enable based on a short VBA script to tell me if it is or not.

Anybody got any ideas as this is getting more than a little frustrating? Thanks

(Excel 2016)

[SOLVED] copy specific column to another sheet after filtered data without header

$
0
0
Hi

My code below works fine, but it copies all data to another worksheet. My data has 21 columns. When I execute the following code, it copies all 21 columns data without header to another worksheet. so if I just want to copy data in column 2 and column 21 without header to another worksheet, how do I modify the code?

Code:

Sub filter_test()

    Dim rang As Range
   
    Set wt = ThisWorkbook.Sheets("Sheet1")
   
    wt.UsedRange.AutoFilter field:=21, Criteria1:="<>0", Operator:=xlFilterValues
   
   
    Set rang = wt.UsedRange.Offset(1, 0)
    Set rang = rang.Resize(rang.Rows.Count - 1)
    Set rang = rang.SpecialCells(xlCellTypeVisible)
   
    rang.Copy ThisWorkbook.Sheets("Sheet2").Range("A1")


End Sub

Form Validation and Insert Object Questions

$
0
0
Hi there fellas,

I'm not that versed in excel let alone VBA, but I usually search for what I need (formulas and macros) and get it done, as most of the stuff I do in excel is rather simple. I've been searching online for a couple of hours now but I couldn't find what I need.

I pretty much need a validation message for a form (plenty of info and videos on this) however I'm not using the "Form" command - which I believe is mostly used for data entry, I created text boxes and a couple of buttons as this will be a unique form completed once by the person that receives it.

  1. With that said I need to have all fields or a way to select fields to be mandatory and to get an error message (highlighting the missing fields if possible) when the user tries to saves the document.
  2. I also need a macro to attach documents into excel (pdf, jpg, etc.) I got one on the file I attached that worked to browse files but other users cant open the objects. Having the objects on a particular cell instead of the active cell would be ideal. If this is complicated maybe a button that attach embedded documents (using the macro I already got) along with the excel form into an email could do the trick.

Hopefully those two are easy to solve, I attached the file I'm using.

Thanks in advance for the support and sorry if I'm asking for too much!

ActiveX MultiPage Control Blues

$
0
0
Hi everyone!

My problem is as follows. I succeded in embedding a Multipage control directly into a sheet and then, adding other controls to a couple of tabs (first selecting the MultiPage control, right clicking it and selecting the modify MultiPage Control option and selecting other activeX controls to drag to their intended posisitions). All of this worked! When exiting the Design Mode, the controls embedded within the MultiPage control didn't disappear. Blissfully I saved my work thinking about resuming my tinkering a couple of days later. Now when in design mode, I can't neither add new controls nor even select the ones that already exist. Aside from all this, I've read that it'll be pretty hard to detect user's intereactions with the controls embedded in the MultiPage. SEE LINK TO FILE.

Thanks!!

https://1drv.ms/x/s!Aj3pTid0W4cOgcco...TLbcA?e=FfNnVI

My ActiveX MultiPage Control Blues

$
0
0
Hi everyone!

My problem is as follows. I succeded in embedding a Multipage control directly into a sheet and then, adding other controls to a couple of tabs (first selecting the MultiPage control, right clicking it and selecting the modify MultiPage Control option and selecting other activeX controls to drag to their intended posisitions). All of this worked! When exiting the Design Mode, the controls embedded within the MultiPage control didn't disappear. Blissfully I saved my work thinking about resuming my tinkering a couple of days later. Now when in design mode, I can't neither add new controls nor even select the ones that already exist. Aside from all this, I've read that it'll be pretty hard to detect user's intereactions with the controls embedded in the MultiPage. SEE ATTACHMENT.

Thanks!!
Attached Files

Macro which sorts and matches entries not working but not erroring

$
0
0
Hi all,

I've done some programming in Python and R but this is my first foray into VBA so my apologies if any of this turns out to be an absurdly stupid question!

I'm trying to write some VBA code which will do the following two tasks.

1: Sorts a range of data by Name and then by Absolute Value

2: Looks through the sorted data, and if two rows have the same Name and Values which sum to zero, deletes both rows.

As it stands, the code I've written works some of the time, but not all of the time. I've attached a spreadsheet with examples of where it works and where it fails. The code behaves as expected for "Anna" and "Tom" but fails for Jack. It should delete both entries as the names are the same and the values are the same.

Any advice would be greatly appreciated.

The code is as follows (a text box is assigned to the first piece of code (Sort_And_Match):

Code:

Sub Sort_And_Match()

Application.ScreenUpdating = False


counter = 0

SortMultipleColumns
Matching

If counter = 1 Then
    SortMultipleColumns
    Matching
   
End If


   
Application.ScreenUpdating = True

End Sub

Code:

Sub Matching()

Application.ScreenUpdating = False

Numrows = Range("A1", Range("A1").End(xlDown)).Rows.Count

Set Rng = Range("A2:A" & Numrows)


For Each Cell In Rng
    RowNumber = Cell.Row
    RowNumberPlus = RowNumber + 1
   
    If Range("B" & RowNumber) = -Range("B" & RowNumberPlus) Then
   
        If Range("A" & RowNumber) = Range("A" & RowNumberPlus) Then
            Range("A" & RowNumber).Resize(2).EntireRow.Delete
            counter = 1
           
           
           
        End If
    End If
   
    Next Cell


End Sub

Code:

Sub SortMultipleColumns()

Numrows = Range("A1", Range("A1").End(xlDown)).Rows.Count
Set Rng = Range("A2:B" & Numrows)

Columns("C").EntireColumn.Insert


For Each Cell In Rng
    RowNumber = Cell.Row
   
    Range("C" & RowNumber).Value = Abs(Range("B" & RowNumber))
   
     
    Next Cell


With ActiveSheet.Sort
    .SortFields.Clear
    .SortFields.Add Key:=Range("A1"), Order:=xlAscending
    .SortFields.Add Key:=Range("C1"), Order:=xlAscending
    .SetRange Range("A1:C" & Numrows)
    .Header = xlYes
    .Apply
   
    Range("C" & RowNumber).EntireColumn.Delete

End With
End Sub

Attached Files

[SOLVED] Looking for help with an if then function

$
0
0
I am not sure if this would fall under VBA or cell formula. Basically what I am doing is making a number comparative, using a cell as a search box. What I am trying to do is turn the search cell (I7) red if there are no matches and green if it matches one of the numbers in column 1. Any help would be much appreciated. ( I have tried a few different codes and couldn't get it to work)
Attached Files

hiding rows based on a value in a column

$
0
0
Hello everyone,

I have a spreadsheet with data in the range D16:G1500

Please how would I write a macro that looks at the value in column D in reach row of the range and if the value is blank "" then it hides the row?
I dont want to use a worksheet change as the data is arranged in a pivot-table and I would like to make selections from the pivot table and then set the macro to hide the rows without data in column D.

Thank you very much, Lucy
Viewing all 49825 articles
Browse latest View live