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

Power Query Table Manipulation

$
0
0
Hi All.

I have a query to an odbc to get my sales forecast by Year 1, Year 2, Year 3... and Start year. I want to convert the table to something more usable. Example below. Top is how I get the data, bottom is what I want I have done it in vba, but how to do it in Power query?

Capture.JPG

Thanks
Steve

Combine a Variable and Constant Sheet Name in VBA

$
0
0
Hello,

I am using a macro to take a master sheet and break it out into sub sheets based on a parameter entered by the user. The code is then renaming the new sheets based on this parameter. I'd like to rename the sheet based on the variable parameter plus a constant value. For example:

If the data is:
Apple
Orange
Banana

I'd the sheets to be named Apple.Fruit, Orange.Fruit, Banana.Fruit.

Thank you for your help!:confused:
Code:

Set Fsheet = ActiveSheet

iCol = ColHeadCell.Column
'loop through values in selected column
For iRow = 2 To Fsheet.Cells(65536, iCol).End(xlUp).Row
  If Not SheetExists(CStr(Fsheet.Cells(iRow, iCol).Value)) Then
      Set Dsheet = Worksheets.Add(After:=Worksheets(Worksheets.Count))
      Dsheet.Name = CStr(Fsheet.Cells(iRow, iCol).Value)
      Fsheet.Rows(1).Copy Destination:=Dsheet.Rows(1)
  Else
      Set Dsheet = Worksheets(CStr(Fsheet.Cells(iRow, iCol).Value))
  End If
  Lrow = Dsheet.Cells(65536, iCol).End(xlUp).Row
  Fsheet.Rows(iRow).Copy Destination:=Dsheet.Rows(Lrow + 1)
Next iRow
End Sub

Moderator's note: Please take the time to review our rules. There aren't many, and they are all important. Rule #2 requires code tags. I have added them for you this time because you are a new member. --6StringJazzer

Excel Macros Disappear

$
0
0
Hi all,

I have installed a set of Excel Macros into my excel. They were working original (with the tab showing up in the ribbon) but have since disappeared. I followed many troubleshooting steps including unblocking the source file within it's add-in folder location and adding the add-in folder location to trusted locations within the trustcenter. However, I still cannot get the macro to re-appear and work in my excel. Any suggestions on how this could be fixed? Appreciate the help

[SOLVED] print excel pivot table

$
0
0
hi, i have this vba code to print a pivot table, however its just prints out ALL of the transactions, i just want the collapsed summary of the table (which is collapsed (filtered) on the screen)
Code:

Private Sub PrintQuaters_Click()
Sheets("Sales Summary").PivotTables(5).TableRange2.PrintOut
End Sub

Getting several codes to run at once and copying cells to another sheet

$
0
0
Hi,

So, I posted a thread the other day regarding a problem of mine (which I am not allowed to post the link to because I am too new to the forum) :).


Basically I run an equation by changing a cell value on a different sheet, let's call that cell value for "D8" and the sheet for "Value sheet". I then have a cell at another sheet which is "C7" on what we can call "Equation sheet". on the "C7" cell I have used the simple command "='Value sheet'!D8" to get the value from the cell that I change the value on.
I then run the following script to solve the equation (the goalseek function):

_______________

Private Sub worksheet_calculate()
Application.EnableEvents = False
Dim Xrg As Range
Set Xrg = Range("C6:C7")
If Not Intersect(Xrg, Range("C6:C7")) Is Nothing Then
Goalseek
Application.EnableEvents = True
End If
End Sub
________
NOTE: This code is at the "Equation sheet"

So, I now want to have another sheet that we can call "Solution sheet" where I basically want to have several columns with empty values with one exception which would be a column with a dropdown box where I can select between 14 values or so.
I then want about twenty rows where I can change one column from the dropdown box described above, which by it self is no trouble making.
So, by changing a value in one of the rows in the "Solution sheet" I want the value that I change to transfer to the "Value sheet", which again will run the program.

To solve this I got the following tip the other day:

_______________________
Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("A10:A20")) Is Nothing Then Exit Sub

' Your code here

End Sub
____________________________

I have not tried it yet, but I am wondering on which sheet this one should by pasted? I guess it has to be the "Solution Sheet" since it has no reference to another sheet.

So, let's say that I made it so far. Now when the code runs and solve the equation for the selected variable, I want it to immediately copy 6 values that we get from the equation into the "Solution sheet". But I need the values to be copied to the same row that I changed the value, and after they are copied I want them to stay there until I change something on the same row again.

I want that for all the 20 rows.

I have tried so much by myself but sometimes it feels like I am shooting in the dark ;) Any help is highly appreciated!

Please feel free to comment if anything is not clear.

increment time in random for each ID vba

$
0
0
Hi I'm trying to increment the time in range size at least ( 2 min to 10 minute ) for each same ID in vba code example table:
ID time
1 5:5
1 5:7
1 5:9
2 10:10
2 10:15
2 10:20

Code:

Private Sub incrementTime_Click()
Application.ScreenUpdating = False
Dim c As Range
Dim lastRow As Long
lastRow = Cells(Rows.Count, "C").End(xlUp).Row
    For Each c In Range("C2:C" & lastRow)
        c.Value = c.Value + 0.002
        c.NumberFormat = "HH:MM"
    Next
Application.ScreenUpdating = True
End Sub

the attachment first sheet is my data the result I except is in second sheet , in sheet2 I add for the ID=1 Time+2 min and ID=2 Time+4
I didn't know how to it any idea for that?
Attached Files

VBA to paste range skipping filtered rows & what is the range copy buffer called

$
0
0
Just had a great idea for a macro for something that always bugged me. When you paste a range over a filtered table, it will paste into the hidden rows. Why not VBA that away?

What's the name of the paste buffer (the excel "clipboard") when you're copying a range versus copying inside a cell? If I know the name, I think i can work with this directly in VBA or do more research.

I got the following code to work. This helps because I don't want the macro to select the range to copy. I want the person to have already selected it.

Code:

Sub pasteClipskiphidden()
'pastes contents of clipboard skipping filtered or hidden rows
Dim cell As Range
ActiveCell.PasteSpecial xlPasteValues, SkipBlanks:=True
End Sub

(I don't want to paste special. I just want to paste but there is no method in intellisense. pastevalues is fine for now)

if I know the name of the "copy buffer object", I can see if it's a collection or list or if it can be parsed or split. Once it is split into a list, I can iterate through it and I think I can handle it there. I can just check for the visibility properties of rows. We'll cross that bridge when we get to it.

(There's surprisingly little written about the two types of copy and paste in excel and the underlying mechanics. I don't meant the types of paste special. I mean copying a range vs copying in a cell.)

VBA and Modules

$
0
0
I have my personal workbook that I've stored all my macros in. There are 25 different modules. My question is should I worry about that? Should I clean them up and put them together or does it really matter? What is the best practice going forward with macros and the modules?

Thanks in advance

generate numbers just in first cell for each user vba

$
0
0
Hi I want to generate random numbers between (5000 to 7000) just in the first cell of column I for each user in column A my code is generate for whole column how can I fix it:
Code:

Private Sub firstprice_Click()
Application.ScreenUpdating = False

    Dim firstprice As Range, rng As Range, rng1 As Range, x As Integer, N As Long
   
    N = Cells(Rows.Count, "A").End(xlUp).Row
    Set rng = Range("I2:I" & N)
      For Each firstprice In rng
        Select Case Int(Rnd * 10) Mod 2
        Case 0: lb = 5000: ub = 7000
        End Select
        x = Int((ub - lb + 1) * Rnd + lb)
        Do While Application.WorksheetFunction.CountIfs(rng.Offset(, -1), firstprice.Offset(, -1), rng, x) >= 1
            x = Int((ub - lb + 1) * Rnd + lb)
        Loop
        firstprice = x
    Next
  Application.ScreenUpdating = True

End Sub

my attachment in the first sheet is the result of code and the second sheet what I except, any idea for that?
Attached Files

[SOLVED] Hide Sheets Error

$
0
0
Hi,

If I run the 'HideCalendarSheets()' when the sheets are already hidden it goes to debug. Is there a way to exit the code if the sheets are hidden?

Thank you

Code:

Sub UnhideAllSheets()

'Unhide all sheets in workbook.

Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets

ws.Visible = xlSheetVisible

Next ws

End Sub


Sub HideCalendarSheets()

'Hide all calendar sheets in workbook.

Sheets(Array("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12")).Visible = False


End Sub

How to block Merge Function?

$
0
0
I want to allow users limited ability to format cell fonts, borders and fill.

I execute the following command: Application.CommandBars.ExecuteMso "FormatCellsDialog" from a custom context menu, but the Merge cells option is there.

I don't want to allow users to see or use the Merge cells feature.

The only choices I know of are these:
1. Prevent users from selecting more than 1 cells
2. Unmerge cells if the cells are merged - I can't use this, as merging cells ruins the format and contents of some of the cells in the merged area that can't be fixed.
3. Application.Undo - I can't get this to work. I run the following code:

Code:

if selectrange.MergeCells then
 application.undo
end if

and it errors out.

So in other words, the only real option I know of, is option 1. Is there a better solution? Ideally I just want a smaller set of format options. Thanks!!

Hide definted worksheets based on given condition

$
0
0
Hi- Im attempting to hide sheets 26 and 27 if A1="Fiscal Year End". It works fine when condition is met but if subsequently that condition is False then sheets 26 and 27 remain hidden. My expectation is that they should be visible again. What am I missing in the code down below? thanks
__________________________________
Sub ConditionalHide()
Dim cRange As String
cRange = "Fiscal Year End"

If Range("A1").Value = cRange Then
Sheet26.Visible = True
Else: Sheet26.Visible = False
End If

If Range("A1").Value = cRange Then
Sheet27.Visible = True
Else: Sheet27.Visible = False
End If

End Sub

Deactivate Excel without minimizing it

$
0
0
Hello all!
This one is a little different... I have 2 monitors. I have Excel open on 1 monitor and some other app open on the other.... could be anything but it will always be the last active app before Excel.
All I need to do is run a macro that will deactivate or make the Excel app lose focus without minimizing it, so the app on the other monitor becomes the active app, same as if I were to click on the other app. I'm pretty sure the fact that the other app is on a different monitor is irrelevant... they could both be on the same monitor and the same macro would work.
Any way to do this with a macro?

I appreciate your help. This has become a challenge for me and I can't figure it out.
Thank you!

Sending Email to list of addresses from worksheet

$
0
0
Hi All,

I want to send an email to a list of email addresses located on a worksheet. I had hard-coded the addresses previously, but I know have to keep these in a worksheet instead. I have setup the following code that appears to be almost ready, but I am missing something here. I get an error at this line:

.To = ws.Range("A" & i).Value , error is "Object doesn't support this property or method"

Any thoughts?

Code:

Sub Email_Click()

Dim IsCreated As Boolean
  Dim i As Long, DesktopPath As String
  Dim PdfFile As String, Title As String
  Dim OutlApp As Object, OutlMail As Object
  Dim ws As Worksheet ' Added for Email Address List
  Dim lRow As Long 'Added for Email Address List
 
  ' Define PDF filename
  PdfFile = ActiveWorkbook.FullName
  i = InStrRev(PdfFile, ".")
  If i > 1 Then PdfFile = Left(PdfFile, i - 1)
  PdfFile = PdfFile & "_" & ActiveSheet.Name & ".pdf"
    ' Enter Subject / Title for email  below:
  Title = "Recap for  " & Range("M2").Value

     
  ' Export activesheet as PDF
  With ActiveSheet
    .ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
  End With
 
  ' Use already open Outlook if possible
  On Error Resume Next
  Set OutlApp = GetObject(, "Outlook.Application")
  If Err Then
    Set OutlApp = CreateObject("Outlook.Application")
    IsCreated = True
  End If
  OutlApp.Visible = True
  On Error GoTo 0
 
  ' Reference Email sheet
  Set ws = ThisWorkbook.Sheets("Email")
 
  'Check columns, and pull names from all rows.
  With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
 
 For i = 1 To lRow
 Set OutlMail = OutlApp.CreateItem(0)
 
  ' Prepare e-mail with PDF attachment
 
  With OutlApp
    ' Prepare e-mail
   
    .To = ws.Range("A" & i).Value
    .CC = ws.Range("E" & i).Value
    .Subject = Title
    .Body = "Hi," & vbLf & vbLf _
          & "The Recap for today's shift is attached in PDF format, open to view." & vbLf & vbLf _
          & "This auto generated email was generated by the following user account:" & vbLf & vbLf _
          & Application.UserName & vbLf & vbLf
    .Attachments.Add PdfFile
 
    ' Try to send or Display
    On Error Resume Next
    .Display
    '.Send
   
    Application.Visible = True
    'If Err Then
    ' MsgBox "E-mail was not sent", vbExclamation
    'Else
    '  MsgBox "E-mail successfully sent", vbInformation
  ' End If
    On Error GoTo 0
 
  End With
 
  ' Delete PDF file
  Kill PdfFile
 
  ' Quit Outlook if it was created by this code
  If IsCreated Then OutlApp.Quit
 
  ' Release the memory of object variable
  Set OutlApp = Nothing
 Next i
 End With
End Sub

VBA merge to multiple rows

$
0
0
I have code below that merges many columns into one cell, at row 5

How do I modify it so that it does more than just row 5, say rows 6 to 20 e.g.?

"K6" will have all the n6:z6 merged
K7 will have all the n7:z7 merged etc.

And if possible when all done, remove the last character ~ from all those cells, K5:k20

Pete

Sub MergeCells()
Dim xJoinRange As Range
Dim xDestination As Range

Set xJoinRange = Sheets("STATS(H)").Range("N5:z5")
Set xDestination = Sheets("STATS(H)").Range("K5")
temp = ""
For Each rng In xJoinRange
temp = temp & rng.Value & "~"
Next
xDestination.Value = temp

'need to keep looping down each row to the 20th row??

End Sub

TRUE/FALSE response if cell value matches any column in same row of vlookup

$
0
0
I'm trying to make a training aid.
In worksheet 1, I have a list of road names and in the columns alongside are all of the grid references that said road appears in my map.
Sheet 2 has a button that will generate a random road name from the list.

I want to type in a grid reference into a box, hit another button, and if the grid reference matches any of those that the road appears, have the word "correct" appear.

I'm self taught, and this is proving way harder than I think it should. I don't need to have the buttons, but think it works better with them.

Appreciate any help.

Automatically copy down formulas when data entered in new row

$
0
0
I have a shared spreadsheet for tracking recruitment and have separate columns with formulas in them. I would like a macro that automatically copies down formulas when I have a user input data in the last empty row of column A e.g. a coworker enters enters data into A:56 and formulas from corresponding columns T, Y, Z, AM etc are copied onto the same row. I know this is possible with a table, but I want to avoid coworkers sorting the table and putting things out of sequence, as we have processes outside of Excel that requires me to quickly see the latest data input towards the bottom without having to wonder if someone sorted the table without me knowing.

[SOLVED] Extract Email Domain

$
0
0
Hello!

I have a big list of information where I need to extract all email domain. The array formula works pretty good in a small set but it keeps crashing on big one.

Kindly check attached sample.

Thank you!!!
Attached Files

Worksheet_selectonChange event problem

$
0
0
Hello,

I have the below codes that take user inputs and make a date using excel EOMONTH function. However, I need to modify it so that cell D41 is treated differently than D43:D51 (if D41 is selected, I need it to be DateSerial(strYear, strMonth, 1) - take first day of the month, not the last. Can someone please help?

PHP Code:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  
Dim strYear As StringstrMonth As String
  Dim criticaldates 
As Range

    Set myRange 
Intersect(Union(Range("D41"), Range("D43:D51")), Target)
    If 
Target.Cells.Count 1 Then Exit Sub
If Not myRange Is Nothing Then

  strYear 
InputBox("Insert Year Number in the format of ""2020""""Year"2020)
   
strMonth InputBox("Insert Month Number in the format of ""1"" or ""12""""Month"1)
   If 
strYear "" Or strMonth "" Then Exit Sub

   
If CInt(strMonth) < Or CInt(strMonth) > 12 _
   Then
    MsgBox 
"You entered invalid year/month information, click on the cell to retry."
    
Exit Sub
    
Else
    
Target.Value Application.WorksheetFunction.EoMonth(DateSerial(strYearstrMonth1), 0)
    
End If

End If
End Sub 

thanks,

reference sheets with matching names, that don’t exist yet

$
0
0
Reference cell data, using data selected on two other sheets that don’t exist yet, one in a different workbook.

Sorry if this is a bit wordy but not sure how else to ask this!

I insert a template into Book 1. When I select a certain value from a drop down menu on the template I'd like the cell in column 3 of the table to reference a cell that from a sheet that will have the same sheet name but in a different workbook (book 2).

The first issue I’m having is that a dynamic sheet reference on the template will not work. When the template is inserted into book 1, the sheet with the data in workbook 2 will exist, but does not exist yet.

Both sheets are automatically named through VBA based on a cell value( in cell A4) of each sheet . (so, if it’s any easier to search sheets for a matching cell value instead of sheet name, then that would work as well, provided the second sheet in book 1 can be ignored [it has a sheet name in A4 but different data] )
Cell A13 is the destination cell in the template, and the source cell will be named; "H_Description" (however every sheet in book 2 will have a cell named “H_Description”).
The next issue I have is that the cell I want the data to appear in (A13), already has a formula, referencing a table on a different sheet that I’d like to keep. However, that would mean the formula or VBA I’m looking for would actually need to be linked to the corresponding cell in the table that is referenced.


Both workbooks will be open when doing this.

Sheets will be added to both books on an ongoing basis.

Book 1 and Book 2, reference the same client list in book 2.

I tried to Attach examples which might describe what I’m trying to achieve better than I've articulated here but was denied because of a "SQL injection"... not sure what that means so will have to look into this to see if I can add some attachments to help.
Viewing all 49987 articles
Browse latest View live