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

Create a macro to to copy data from one sheet to another

$
0
0
Hello, I am a beginner on Excel Macros and found this forum.

Here is my question -

I have file A, which has data in certain columns. I wanted to know if there is a way to create a Macro to copy and paste the data in file A into file B (in specific columns). File B remains the same, there will be multiple versions of file A.

Since I will have to do it for a lot of files, I wanted to know if there is a way to create a macro for this function, where the data is automatically copied and pasted into file B. I am assuming that file A would need to be defined each time, but if any help can be given on this, it will be great.

Thanks!

[SOLVED] Reference to second pivot table not working

$
0
0
I'm very new to VBA but I know how to record macros and I tried doing that for a report I run monthly. In the report, I make a pivot table of some data to sum up the data by country. I then highlight the pivot table and paste it below the current pivot table to create a second pivot table and go from there summing up the data by customer and adding in a whole bunch of other stuff. The macro keeps getting hung up on the first reference to the new pivot table when I run it and I'm not sure why. I tried changing the activesheet.pivottables part to sheets("sheet1") to actually reference the sheet I'm working in as some post online recommended but it still got hung up.

Below is the code where it's getting stuck. I'm assuming the issue is that it can't find pivottable2 for some reason but I don't know why or how to name a pivot table in the middle of code much less how to change all the following code after this section that refers to it as ActiveSheet.PivotTables("PivotTable2"). Any help is appreciated

Range("A1:E11").Select
Selection.Copy
Range("A18").Select
ActiveSheet.Paste
With Sheets("Sheet1").PivotTables("PivotTable2").PivotFields("Customer") <----- highlights this line as the issue.
.Orientation = xlRowField
.Position = 1
End With

NEVERMIND I JUST DISCOVERED FOR SOME REASON THE PASTED PIVOT TABLE IS LABELED PIVOTTABLE3 FOR SOME REASON. I WOULD DELETE THIS IF I COULD.

VBA issue creating new workbook with range

$
0
0
Hello,

I am trying to figure out a VBA code for creating a new workbook with data paste- but I seem to keep getting errors with whatever changes I make. Essentially I am trying to have excel (VBA) take a range from the active sheet in a workbook (under a locked worksheet/workbook), create a new workbook and paste the copied range to cells A1. Seems relatively simple but I think I may be having issues because the workbook and sheet are locked and issues referencing the activesheet instead of a specific sheet name. The workbook where the range is copied from will have a name though. (I can make a reference to the password in another cell for it to unlock- but I cant seem to get excel to do this correctly)

I included a simple code below but when I am trying to reference the activesheet it gives a subscript error. Also, I am having issues addressing the locked workbooks and sheets.

Any help would be greatly appreciated.

Thank you.

Code:

Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("WorkbookName.xlsx").ActiveSheet.Range("A1:K10").Copy
  NewBook.Worksheets("Report").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs Filename:=NewBook.Worksheets("Report").Range("E3").Value
End Sub

separate the numbers from the 4th position to the 12th position.

For Loop Skipping last value for certain range of values

$
0
0
Hi, I wrote the following code using a for loop:

Sub test()

Dim n As Double, t As Double
t = 1.5

Range("A2").Select

For n = 0 To t Step 0.1

ActiveCell.Value = n

ActiveCell.Offset(1, 0).Select

Next n
End Sub

This is supposed to output values from 0 to 1.5 in column A at 0.1 intervals.

The issue I'm facing is that for values upto t=1.3, the last output value is 1.3, However if I put t=1.4 it still gives the last value as 1.3

if t=1.5, last output value is 1.4! for t=1.6 last output is 1.7 and so on...

This continues till t=4.7, after which for t=4.8 last value is also 4.8


Any suggestions on what's going on?

Help with attendance record

$
0
0
Hi,

I'm new here, haven't used macros for a couple of years. My problem is with attendance record, it shows the users, the date, and all the hours they use the system. What I need is to show a sheet with the users, the date and first and last use of the system, just two records by day (entry and leave).
Attached Files

Need Help with Macro Compile Error

$
0
0
I have Excel 2016 and I export a list of checks from my accounting program. I recorded a macro to make the adjustments to the file - formatting, columns, etc. I had no problem in an older version of Excel with this, but now in Windows 10 and Excel 2016 when I record it fresh, I am getting an error message when I try to run it. So far it's highlighting the first line which looks like it's where I select the header row and delete it. Then I insert a column in A1 and put in my Routing number and copy it down, then I format the date and add a column for the code 320. That's pretty much it.

I don't understand what the problem is.

Code:

Sub Fraud()
'
' Fraud Macro
'
' Keyboard Shortcut: Ctrl+Shift+J
'
    Rows("1:1").Select
    .  := xlUp
    Columns("A:A").Select
    .Accelerator  := xlToRight,  := xlFormatFromLeftOrAbove
    Range("A1").Select
    . = "1111111111"
    Range("A1").Select
    .  := Range("A1:A17")
    Range("A1:A17").Select
    Columns("E:E").Select
    . = "$#,##0.00;[Red]-($#,##0.00)"
    Columns("F:F").Select
    .Accelerator  := xlToRight,  := xlFormatFromLeftOrAbove
    Range("F1").Select
    . = "320"
    Range("F1").Select
    .  := Range("F1:F17")
    Range("F1:F17").Select
    Columns("F:F").Select
    . = "0_);[Red](0)"
    Columns("D:D").Select
    . = "mm-dd-yyyy"
    Name.Rows
    DisplayRightToLeft("PERSONAL.XLSB").
    Name.Rows
End Sub

If you have any ideas to figure out why it's giving me syntax errors THANK YOU for sharing! :)

Carla

Workbooks.open fails when run from macro

$
0
0
Excel 2019 Windows 10

Have a large wb that takes maybe 6 seconds to unpack itself. Been running it from a macro for years under excel 2007 without much issue

Now, it randomly (but MOST of the time) simply fails to complete loading and hangs Excel when run that way (not responding, has to be force closed)

When the same file is run from the Excel file manager, no problem. opens with no errors

called with :
Workbooks.Open filespec

simple call is used, no vars, no objects.

Tried a bunch of things, all seem to fail. Funny thing is, it sometimes works, then the next day will fail again with the same code.

The workbook.open event is not firing when it fails, as I have a 'speak' line in there that would tell me it had.

Copying data based on criteria

$
0
0
Dear Gurus,

I stacked with small problem as new to VBA coding. I need a macro which will copy data from initial table, but taking into account pre-defined "code".

Thank you in advance for any ideas which can helps. Example in attachment with my manual solution + color coding for better understanding.

With Best Regards,
Igor
Attached Files

Worksheet References using Object Variable

$
0
0
I have a workbook with 2 worksheets: sheet1 and sheet2. I am attempting to populate an array (mntharray) from the Range "A6:D10." This range is not fixed and can have more or fewer rows so a formula is used to compute it. Here is the simplified code.

/
Sub test()

Dim mntharray() As Variant
Dim numrows As Integer
Dim sheet1WS As Worksheet

Set sheet1WS = Sheets("Sheet1")
numrows = 5
ReDim mntharray(numrows, 4)

mntharray = sheet1WS.Range(Range("A6"), Range("D" & numrows + 5))

End Sub
/

Here is the issue. If I have the focus on sheet 1 (sheet1 is selected in the Excel worksheet) and I run the code, it runs fine. If the focus is on sheet2, I get the "Run-time" error, Range of object failed.

My understanding is that by defining the object variable sheet1WS, this is sufficient for VBA to determine the reference for mntharray. An important observation is that if the line
mntharray =sheet1WS.Range("A6:D10") the code works as I would expect, regardless of the focus. Obviously, my understanding is wrong and there is a small complexity added with the more complicated formula in mntharray. Can you explain this to me?

Macro to input formula in missing D column and undo merge cells in a certain range

$
0
0
So I have a worksheet that when freelancers enter in the days of the week they have off (in cells N4:N6), the time formula is deleted in D in every row for that day of the week, and columns E:R are merged with the words DAY OFF for that day of the week.

The macro I coded works great! SO this is what it looks like after the days off macro has been run:

example days off.png

Next to every Friday and Sunday, the formula in D has been cleared and E:R are merged with the words "DAY OFF."

Macro I coded to do that:

Code:

Sub DaysOff()

    Dim rngAlldays As Range
    Dim c1 As Range, c2 As Range, c3 As Range
   
    Set rngAlldays = Worksheets("Scheduler").Range("A10:A450")
   
   
    If ActiveSheet.Range("N4") <> "" Then
    'Do Nothing
   
   
    For Each c1 In rngAlldays
        If c1.Value = ActiveSheet.Range("N4") Then
            c1.Select
            ActiveCell.Offset(0, 3).ClearContents
            c1.Select
            ActiveCell.Offset(0, 4).Value = "OFF DAY"
            Range(ActiveCell.Offset(0, 4), ActiveCell.Offset(0, 17)).Select
            With Selection
            .HorizontalAlignment = xlCenter
            .VerticalAlignment = xlBottom
            .Merge
            End With
   
        End If
        Next c1
       
    End If
   
    If ActiveSheet.Range("N5") <> "" Then
    'Do Nothing
   
   
    For Each c2 In rngAlldays
        If c2.Value = ActiveSheet.Range("N5") Then
            c2.Select
            ActiveCell.Offset(0, 3).ClearContents
            c2.Select
            ActiveCell.Offset(0, 4).Value = "OFF DAY"
            Range(ActiveCell.Offset(0, 4), ActiveCell.Offset(0, 17)).Select
            With Selection
            .HorizontalAlignment = xlCenter
            .VerticalAlignment = xlBottom
            .Merge
            End With
   
        End If
        Next c2
       
    End If
       
   
    If ActiveSheet.Range("N6") <> "" Then
    'Do Nothing
   
   
    For Each c3 In rngAlldays
        If c3.Value = ActiveSheet.Range("N6") Then
            c3.Select
            ActiveCell.Offset(0, 3).ClearContents
            c3.Select
            ActiveCell.Offset(0, 4).Value = "OFF DAY"
            Range(ActiveCell.Offset(0, 4), ActiveCell.Offset(0, 17)).Select
            With Selection
            .HorizontalAlignment = xlCenter
            .VerticalAlignment = xlBottom
            .Merge
            End With
   
        End If
        Next c3
       
    End If

End Sub

QUESTION: NEED TO CODE RESET BUTTON

But if the user no longer has Friday off later on in the year, I want to code a reset button where for all the Fridays (or whatever day off they put in N4) the formulas will be restored and the cells not merged. But I can't figure out how to reset the formulas. Everything i tried didn't work. I did get the unmerge part to work.


The formula is the same as the row above it. So for example if Friday is in row 45, then I just need the code in row 44 to be copied down with the row number changed to 44.

This is the formula:
Formula:
=CHOOSE(WEEKDAY(B15,2),$J$4,$J$5,$J$6,$J$7,$L$4,$L$5,$L$6)-C15
(where the row number [15 in this example] changes depending on the row the formula is in.

Any ideas on how I could reset the formula in this code:

Code:

Sub Reset()

    Dim rngAlldays As Range
    Dim c1 As Range, c2 As Range, c3 As Range
   
    Set rngAlldays = Worksheets("Scheduler").Range("A10:A450")
   
    If ActiveSheet.Range("N4") <> "" Then
    For Each c1 In rngAlldays
        If c1.Value = ActiveSheet.Range("N4") Then
          c1.Select
            Range(ActiveCell.Offset(0, 4), ActiveCell.Offset(0, 17)).Select
            With Selection
            .HorizontalAlignment = xlGeneral
            .VerticalAlignment = xlBottom
            .UnMerge
            End With
   
        End If
        Next c1
       
   
    End If
   
    If ActiveSheet.Range("N5") <> "" Then
    'Do Nothing
   
   
    For Each c2 In rngAlldays
      If c2.Value = ActiveSheet.Range("N5") Then
            c2.Select
            Range(ActiveCell.Offset(0, 4), ActiveCell.Offset(0, 17)).Select
            With Selection
            .HorizontalAlignment = xlGeneral
            .VerticalAlignment = xlBottom
            .UnMerge
            End With
   
        End If
        Next c2
   
       
    End If
       
   
    If ActiveSheet.Range("N6") <> "" Then
    'Do Nothing
   
   
    For Each c3 In rngAlldays
        c3.Select
        If c3.Value = ActiveSheet.Range("N6") Then
            Range(ActiveCell.Offset(0, 4), ActiveCell.Offset(0, 17)).Select
            With Selection
            .HorizontalAlignment = xlGeneral
            .VerticalAlignment = xlBottom
            .UnMerge
            End With
        End If
        Next c3
       
    End If

End Sub

Mac Versions of Library Functions?

$
0
0
I have over 60k lines of code, and therefore use many Library functions for all my features to work. I am aware that they only work for Windows machines, and won't work properly for Mac? Can someone give me the Mac equivalents or advise me what to do if my App is run on Mac? Thanks

Code:

' Functions for the custom menu...
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
' Functions for the custom menu...
Private Declare PtrSafe Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
' Functions for the custom menu...
Private Declare PtrSafe Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
' Functions for the custom menu...
Private Declare PtrSafe Function DrawMenuBar Lib "user32" (ByVal hwnd As Long) As Long
' Function for getting cursor position
Private Declare PtrSafe Function GetCursorPos Lib "user32" (lpPoint As XYPosn) As Long
Private Declare PtrSafe Function ClientToScreen Lib "user32" (ByVal hwnd As Long, lpPoint As XYPosn) As Long
Private Declare PtrSafe Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Private Declare PtrSafe Function GetDeviceCaps Lib "gdi32" (ByVal hDC As Long, ByVal nIndex As Long) As Long
Private Declare PtrSafe Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hDC As Long) As Long
Private Declare PtrSafe Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer ' for detecting key presses and mouse clicks

Private Declare PtrSafe Function GetSystemMetrics Lib "User32.dll" (ByVal nIndex As Long) As Long
Private Declare PtrSafe Function GetCurrentThreadId Lib "kernel32" () As Long
Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal X As Long, ByVal Y As Long) As Long
#If Win64 Then '64?
    Private Declare PtrSafe Function MsgBoxTimeout _
        Lib "user32" _
        Alias "MessageBoxTimeoutA" ( _
            ByVal hwnd As LongPtr, _
            ByVal lpText As String, _
            ByVal lpCaption As String, _
            ByVal wType As VbMsgBoxStyle, _
            ByVal wlange As Long, _
            ByVal dwTimeout As Long) _
    As Long
#Else
    Private Declare Function MsgBoxTimeout _
        Lib "user32" _
        Alias "MessageBoxTimeoutA" ( _
            ByVal hwnd As Long, _
            ByVal lpText As String, _
            ByVal lpCaption As String, _
            ByVal wType As VbMsgBoxStyle, _
            ByVal wlange As Long, _
            ByVal dwTimeout As Long) _
    As Long
#End If

' Clipboard
#If Mac Then
    ' do nothing
#Else
    #If VBA7 Then
        Declare PtrSafe Function GlobalUnlock Lib "kernel32" (ByVal hMem As LongPtr) As LongPtr
        Declare PtrSafe Function GlobalLock Lib "kernel32" (ByVal hMem As LongPtr) As LongPtr
        Declare PtrSafe Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, _
                                                            ByVal dwBytes As LongPtr) As LongPtr

        Declare PtrSafe Function CloseClipboard Lib "user32" () As Long
        Declare PtrSafe Function OpenClipboard Lib "user32" (ByVal hwnd As LongPtr) As LongPtr
        Declare PtrSafe Function EmptyClipboard Lib "user32" () As Long

        Declare PtrSafe Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, _
                                                        ByVal lpString2 As Any) As LongPtr

        Declare PtrSafe Function SetClipboardData Lib "user32" (ByVal wFormat _
                                                                As Long, ByVal hMem As LongPtr) As LongPtr
    #Else
        Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) As Long
        Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) As Long
        Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, _
                                                    ByVal dwBytes As Long) As Long

        Declare Function CloseClipboard Lib "user32" () As Long
        Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
        Declare Function EmptyClipboard Lib "user32" () As Long

        Declare Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, _
                                                ByVal lpString2 As Any) As Long

        Declare Function SetClipboardData Lib "user32" (ByVal wFormat _
                                                        As Long, ByVal hMem As Long) As Long
    #End If
#End If

' CURSOR

#If VBA7 Then
    Declare PtrSafe Function LoadCursorLong Lib "user32" Alias "LoadCursorA" _
      (ByVal hInstance As Long, ByVal lpCursorName As Long) As Long
   
    Declare PtrSafe Function SetCursor Lib "user32" _
      (ByVal hCursor As Long) As Long

    Declare PtrSafe Function GetCursorInfo _
        Lib "user32" (ByRef pci As CURSORINFO) As Boolean
   
    Declare PtrSafe Function LoadCursor _
        Lib "user32" Alias "LoadCursorA" _
        (ByVal hInstance As Long, ByVal lpCursorName As Long) As Long
#Else
    Declare Function LoadCursorLong Lib "user32" Alias "LoadCursorA" _
      (ByVal hInstance As Long, ByVal lpCursorName As Long) As Long
   
    Declare Function SetCursor Lib "user32" _
      (ByVal hCursor As Long) As Long
     
    Declare Function GetCursorInfo _
        Lib "user32" (ByRef pci As CURSORINFO) As Boolean
   
    Declare Function LoadCursor _
        Lib "user32" Alias "LoadCursorA" _
        (ByVal hInstance As Long, ByVal lpCursorName As Long) As Long

#End If

Expand Algebraic Formula to Column

$
0
0
I need to expand simple algebraic patterns into a column. The patters has repeat segment like (AB)*5 which need to be displayed as ABABABABAB.
Attached Files

Extract data from Power Point to Excel

Environ conditional

$
0
0
Hi,

I'm using the following code to bring username & date/time stamp - is it possible that if the date doesn't match with cell B6 then it automatically turns Red or circle etc to indicate

Code:

Private Sub Worksheet_Change(ByVal Target As Range)


If Not Intersect(Target, Range("b7:b46")) Is Nothing Then
If Target.Count > 1 Then Exit Sub
Cells(Target.Row, "c").Value = Environ("username") & ", " & Format(Now, "dd.mm_hh.mm")
End If

THank you

[SOLVED] VBA code for copy paste data to active cell

$
0
0
In the attached file in E column you find this names "AKOLA-MANDI, KARANJA-MANDI ,KHAMGAON MANDI, MANGARULPIR MANDI ,AMARAVATI MANDI"
if i want to copy one of that five names for example i want to copy AKOLA-MANDI to any active cell or suppose cell E44 in before sheet
which i mentioned in attached file, it means when i press key combination ctrl+l then copy paste AKOLA-MANDI to active cell,
when i press key combination ctrl+t then copy paste AMARAVATI MANDI to active cell,
when i press key combination ctrl+k then copy paste KARANJA-MANDI to active cell,
when i press key combination ctrl+h then copy paste KHAMGAON MANDI to active cell,
when i press key combination ctrl+m then copy paste MANGARULPIR MANDI to active cell,
so please provide VBA code for above operation
Attached Files

Shift cell content left, replace with space

$
0
0
Hello and thanks in advance.

I have 3 columns with the same number appearing randomly. I'd like them all shifted to the same column, and the vacated cell then have a space or something like an asterisk.

(Note: I posted in Formulas, was advised to post in VBA.)

FROM TO.jpg

Changing font size of a portion of an output in a cell

$
0
0
I have a file in which I added some VBA code to convert numbers to words. I want to increase the font size of the currency name only. Below is the attached file.
Attached Files

Using Item(1) to work with a file

$
0
0
Hi all,
I tried to get a file from a folder (for copy) using the method Item(1) to and I have runtime error.
To work with a worksheet I can use Worksheets.Item1) for .Files I can't

thanks in advance

Kaus Borealis

Opening a word document from inside an Excel spreadsheet

$
0
0
Hi

I'd like to be able to open a word document from inside an Excel Spreadsheet. First of all, is it better to have Word open or does that not matter? Since I am not conversant in VBA I tried to do it by recording. Not successful. Can anyone help? The two files will be in the same folder.

Many thanks

Patish
Viewing all 49828 articles
Browse latest View live