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

Method FIND, to find a DATE in a hidden range

$
0
0
Hi

I discovered the following code on the net to find a certain date in a certain range:

Code:

Sub FindAll()

    Dim FirstFound As String, FirstAddress As String
    Dim StartRng As Range, Rng As Range
    Dim StartDate As Date
   
   
    '
    '  DATE TO FIND  DATE TO FIND  DATE TO FIND
    '
   
    StartDate = DateSerial(Year(Date), Month(Date), 1)
   
    '
    '
    '
   
    Set StartRng = PLANEAMENTO.Range("P10:BW10").Find(What:=DateValue(StartDate), LookAt:=xlWhole, LookIn:=xlValues)

    If Not StartRng Is Nothing Then
        FirstFound = StartRng.Address
    Else
        GoTo NothingFound
    End If

    Set Rng = StartRng
    Do Until StartRng Is Nothing
        Set StartRng = PLANEAMENTO.Range("P10:BW10").FindNext(After:=StartRng)

        Set Rng = Union(Rng, StartRng)
        If StartRng.Address = FirstFound Then Exit Do
    Loop

    MsgBox Rng.Address ' Rng.Column

    Exit Sub
NothingFound:
    MsgBox "No values were found in this worksheet"

End Sub

Bearing in mind that the native format of my excel is "dd / mm / yyyy", that is, European system, what is wrong with the code so as not to detect where the date is looking for?
The dates in the range are calculated and not entered manually, and are on line 10 and are hidden.

What I need is to find a certain date, in this case 01/04/2020, by the Find method, in a hidden line. It's possible? What's the code?

Thank you for your help
Jorge Cabral
Attached Files

[SOLVED] OptionButtons can they be manually paired?

$
0
0
Hi, I'm using UserForms for the first time and after having used OptionButtons before as the usual Yes/No pair which worked well.
I now have two pairs of OptionButtons very near each other so when I click on one of a pair it is set as True, then when I click on another OptionButton in the other pair and it is set as True and the previous Option Button is set to false. Instead of changing one pair to a pair of text boxes with code is their a way to assign OptionButtons to each other?

Circular reference in unrelated cells

$
0
0
Hi,
I'm stuck with a circular reference that pops up from time to time even though the cells are not related to each other in any formula.
I have to say I am not at all an expert in VBA, I just pasted and adapted some code from around the internet for my needs.

Specifically, changing the data in J4 will show an error in M7. I tried Intersect and just Range for the selection in the code but without luck. Not even sure that is the cause of the problem. Any advise is appreciated. Here is the code and attached the excel file:

Code:

Private Sub Worksheet_Change(ByVal target As Range)

'  If Intersect(target, Range("e11:g11"), Range("m7:n7")) Is Nothing Or target.Value = "" Then Exit Sub
    If Range("e11:g11") Is Nothing Or target.Value = "" Then Exit Sub
        Application.EnableEvents = False
       
'      Stop selection moving to next cell:
        target(1, 1).Select
       
        If Intersect(target, Range("e11")) Is Nothing Then
          Range("e11").Formula = "=1-(g11/f14)"
        Else
          Range("g11").Formula = "=f14-(E11*f14)"
        End If
           
    If Range("m7:n7") Is Nothing Or target.Value = "" Then Exit Sub
       
        If Intersect(target, Range("m7")) Is Nothing Then
          Range("m7").Formula = "=n7/m4"
        Else
          Range("n7").Formula = "=m7*m4"
        End If

        Application.EnableEvents = True
End Sub

Attached Files

Size and position charts

$
0
0
I have two VBA macros now that create charts from data and are working nicely.

There are just two more things are required.

I need to size each chart and then cut and paste them onto another sheet at specific positions.

I think it would be best to do these two steps (size and position) one at a time, as each chart is created.

Any guidance on how I could achieve this would be appreciated!

VBA run-time error 5 invalid procedure call or argument

$
0
0
I sometimes get a VBA run-time error 5 invalid procedure call or argument when writing a large json file to a text file using the following code; has anyone had this before and knows how to solve it?

The error happens when the code gets to file.WriteLine (sContent).

The sContent is a ~700k character string, a json file downloaded from an API.

Code:

Sub SaveToFile(sFileName, sContent)
    'Saves a string to a file and closes the file
    ' sample usage: SaveToFile "d:\test.txt", "test"
    Dim fs As Object
    Dim file As Object
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set file = fs.createtextfile(sFileName, True)
    file.WriteLine (sContent)
    file.Close
End Sub

[SOLVED] Offset formula using active cell

$
0
0
Hi, is anyone able to help me to get this equation to work. The reason for using ActiveCell is because it is part of a macro and the cell will vary.

=(OFFSET((ActiveCell),0,-1))

If anyone is able to help solve the problem that this equation forms part of that would be great too.
It is in the VBA part of the forum called "formula-in-and-offset-cell-based-on-location-of-text" (Not allowed to post links yet)

The VBA code on the post above is:
Code:

Sub Formula()

For i = Last To 1 Step -1
If (Cells(i, "A").Value) = "Grand Total" Then
Activell.Offset(, 2) = Cell
Cell = "=IF(ActiveCell=Sheet1!N55,True,False"
End If
Next

End Sub

Intent: Go down column A until "Grand Total" found, then place formula in offset cell (0,2). The IF formula wants to reference a cell offset (0,-1) as part of the equation.

Thanks all!!
Attached Files

Moving charts from one sheet to another...

$
0
0
Well I am making very good progress now with my code (thanks to the help I am getting here).
And I have been able to get it to work on my desktop running Excel 2002 !

I basically have three macros that I will be using.
The first runs through a list of Station names that are used in creating the charts.
The second macro creates the charts.
And the third macro sizes the charts and positions them on another sheet.

So now all I have to do is find a way to move the charts that have been created with the second macro, onto
the final sheet where they will be re-sized. This is where I could use some help, if possible.

I'm also trying to figure out why the charts are now being created next to the Station names,
whereas in the original code they were all being created at the top of the sheet, one on top of
each other. I don't know if this is a problem or not, for when they will be moved onto the final sheet.

Here are the two main macros:


Code:

Sub FindStation()
 
Worksheets("Names").Select
Range("A1").Select
 
Begin:
 
If ActiveCell = "" Then
   
    GoTo Finish
   
Else
      Call makechart
     
End If
 
  Worksheets("Names").Select
  ActiveCell.Offset(1, 0).Select
  GoTo Begin
 
Call makechart
 
Finish:
 

End Sub

Code:

Sub makechart()


Dim Found As Range
           
    Set Found = Sheets("Sheet1").Cells.Find(What:=ActiveCell.Value, _
                                            LookIn:=xlValues, _
                                            LookAt:=xlWhole, _
                                            SearchOrder:=xlByRows, _
                                            SearchDirection:=xlNext, _
                                            MatchCase:=False)
               
    If Not Found Is Nothing Then
        Application.Goto Found
    Else
        MsgBox ActiveCell.Value, vbExclamation, "No Match Found"
    End If


Dim startrow, finishrow As Integer
Dim chtrange, title1 As String

Worksheets("Sheet1").Select
title1 = ActiveCell.Value
startrow = ActiveCell.Row
finishrow = startrow

Do While Range("d" & finishrow).Value = Range("D" & finishrow + 1).Value
finishrow = finishrow + 1
Loop

chtrange = "Sheet1!$A$" & startrow & ":$C$" & finishrow
   
   
    charts.Add
    ActiveChart.ChartType = xlColumnStacked
    ActiveChart.SetSourceData Source:=Sheets("Sheet1").Range("A11:C19"), PlotBy _
        :=xlColumns
    ActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1"
    With ActiveChart
        .HasTitle = True
               
        .ChartTitle.Characters.Text = title1
        .Axes(xlCategory, xlPrimary).HasTitle = False
        .Axes(xlValue, xlPrimary).HasTitle = False
        '
    End With

End Sub


If someone can help me move the created charts onto a sheet called 'Charts' I'd really be grateful! :)

How to search rows of pivot table and separately do a calculation

$
0
0
Hello all,

I am new to this forum and VBA excel and have a class project (we get to choose our project so there is no set way to do this) in which I have automated so far the creation of a monthly report (in a sense) so far! Hopefully, maybe some of you can help me with this last part.. :). I want to be able to pull data from each individual row of a pivot table to do the same calculation until the last row is reached.

To be concrete, I want the code to be able to automatically search each row in just the pivot table to calculate the mean, max, and percentage of total. I am not sure how I would go about doing this because

1) the number of rows in the pivot table change each month so if i set the pivot table to go down to only row 27 and next month it goes down to row 30 then there is a problem.

2) I also want to move the information (as it would organized like in AC29) and paste it into a new worksheet. the problem is if I am running a loop for the row calculation, then I currently do not have the knowledge to change the Copy&Paste location each time.

Let me know what you all think!! I appreciate any help or advice on methodology, or vba commands that come to mind! Again, I am new to this so I don't have as much knowledge of methodology as you all~. Apologies if my question is elementary.


Annotation 2020-04-12 212324.jpg

Combo Box with Ranges Lists

$
0
0
Is it possible to create a Combo Box that lists a series of different ranges? For example:


Column Name: Neighborhood Population
List Item 1 1 thru 1000
List Item 2 1001 thru 2000
List Item 3 2001 thru 3000
List Item 4 3001 thru 4000
List Item 5 4001 thru 5000

and so on...

Whatever list item I choose will be the search criteria to show only those rows that meet this criteria.

Thanks in advance!

Dan

Searching data in different format against user's input (Macro vba

$
0
0
Hello guys.

I have following problem :( :

User inputs an especific serial number (in a cell, box, etc.) in order to search it in a database, example: 1906234568129

But my database where I need to searg contains this information on 7 different cells (different adyacent column each one) like this: 3031(cellA1), 3930(cellB1), 3632(cellC1), 3334(cellD1), 3536(cellE1), 3831(cellF1), 3239(cellG1).

Any clue what I need to do on my vba searching code? I can not modify original data, just search on it.

I hope you can help me.

Regards.

File Path Problem

$
0
0
With this macro, I merge some tables from different excel files in the same folder .

But it works on desktop, not work in other folders. What is the wrong? I think file path (ThisWorkbook.Path) give problem in the folder.


Code:

Sub a()
Dim aktif As Workbook, sh As Worksheet, a As Long
Dim klasor As Object, evn As Object, xls As Object
Set sh = ThisWorkbook.Worksheets("sayfa1")
Set evn = CreateObject("scripting.filesystemobject")
Set klasor = evn.getfolder(ThisWorkbook.Path)
For Each xls In klasor.Files
If LCase(Mid(xls.shortname, InStr(1, xls.shortname, ".", 1) + 1)) = "xls" Then
If xls.Name <> "ÖRNEK DOSYA.xls" Then
Workbooks.Open (xls.Path)
Set aktif = ActiveWorkbook
a = aktif.Sheets(1).Range("a65536").End(3).Row
aktif.Sheets(1).Range("a2:ak" & a).Copy
sh.Range("a65536").End(3)(2, 1).PasteSpecial xlPasteValues
aktif.Close False
End If
End If
Next xls
a = Empty
Set sh = Nothing
Set evn = Nothing
Set aktif = Nothing
Set klasor = Nothing
End Sub

Attached Files

MERGE Multiple ROWS by month

Audit trail log with User name and date time

$
0
0
Hi everyone.
I am new to this forum and zero knowledge on VBA and need help.

A) I am doing an excel checklist with a maker and checker function. The names should not replace each other. someone (maker) prepare the checklist save and his name appeared in the maker field. and another person (checker) open up the file and check and save again and his name appeared in the checker field.

Hence my Tab1 will be a list of daily checklists and end of the worksheet I need a Maker and checker username populated once they saved the file.

eg.
checklist 1
checklist 2
checklist 3
checklist 4
checklist 5

Maker : [U]Username
Checker: [U]Username

B) then I need Tab 2 to be an Audit trail tab, which capture the saving date/time stamps with user name, date and time.

I have tried some examples in the forum but don't seem to be able to put both function together :(

Cell equal value of active cell which is a drop down

$
0
0
I have a cell which i declared as active cell using developers tool in excel

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Range("C1").Value = ActiveCell.Value

End Sub

So whatever cell i click on, cell C1 will show that Value.

What i want to do it
Cell C1 is working correctly when i click acell, the C1 gets the value of that cell. But my issue is that, i have created drop down from Data Validation in specific cells. At first, when i click that cell , assume B1, C1 get the correct value of that cell, but when i select a new value from B1's drop down, C1 dose not change , it keeps that initial value. Is there a ways to make C1, change when i select a new value from B1's Drop Down?

Delete record in all worksheets with Userform

$
0
0
Hello All,

I have this code and my desire is to delete the record in all sheets at the same time...

I have the main sheet called EmployeeData and I would like to select the name of the employee and have it delete from all sheets...

I have a worksheet for each month and the name of the customer is in each worksheet Jan_Data to Dec_Data etc...

Code:

Private Sub CommandButton1_Click()
 Dim ws As Worksheet
    Dim strSearch As String
    Dim aCell As Range

    On Error GoTo Err

    '~~> Set the sheet where you want to search the IMEI
    Set ws = Sheets("EmployeeData")


    With ws
        '~~> Get the value which you want to search
        strSearch = lstMyData.Value

        '~~> Column A is Column 1 so Column B is 2. This is where we are searching
        '~~> xlWhole is used in the code below so that we find a complete match
        '~~> xlPart is supposed to be used when you are finding a partial match.
        Set aCell = .Columns(1).Find(What:=strSearch, LookIn:=xlValues, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

        '~~> Check if we found the value
        If Not aCell Is Nothing Then
            '~~> get the row of the cell where we found the match and delete it
            .Rows(aCell.Row).Delete
        Else '<~~ If not found
            MsgBox "Agent not Found"
        End If
    End With

    Exit Sub
Err:
    MsgBox Err.Description
End Sub

Your thoughts would be appreciated!

Regards,

John

[SOLVED] VBA Code to highlight Odd and Even numbers

$
0
0
I am trying to write a VBA Function code to highlight Odd and Even numbers. But not having much luck. Can anyone help me, please?

How to Merge two arrays

$
0
0
Hello,

Is there is a way to merge two arrays with 2 different dimensions with vba ( 2 columns, unlimited rows) ?

array1 (a, 2)
array2 (b, 2)

Array 3 ( a+b,2 ) = Merge(array1, array2 )

Thank you ?

Najwa.

[SOLVED] ListBox and ComboBox in UserForm not responding to code

$
0
0
When I open the Userform & tab through controls, this code is not having any effect?

Code:

Private Sub cmbMonth_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)

    If IsEmpty(cmbMonth.Value) Then
        cmbMonth.BackColor = rgbPink
        Cancel = True
    End If
End Sub
Private Sub LstCustomer_AfterUpdate()

    If IsEmpty(LstCustomer.Value) Then
        lblCustomer.ForeColor = vbRed
        Cancel = True
    End If
End Sub

Thanks in advance

Button to save file in two location

$
0
0
Hi Gang,
What is the best way to to save a file in two locations. Should I just record a macro? or is VBA the best code. If it is VBA can someone kindly direct me to a template where I can type in two different locations?

Thank you much.

Stay safe everyone!

Create ready-to-send e-mail in Outlook based on dynamic cell values in Excel

$
0
0
Hello,

I'm pretty new to macros and VBA and would be super grateful for some help with a pet project I've been working on over the past few weeks.

My project is a form where in the first worksheet the user selects various inputs from pre-defined (data validation) lists, which draws corresponding information from other "database" sheets (tables) and compiles it in an "output" sheet, which is basically the entire body of an e-mail, ready to copy and send. The recipient and CC addresses are stored in specific cells in a hidden sheet, and may change depending on the user's input in the first sheet. The from and BCC addresses should also be pre-set, but to a specific e-mail address which will not change depending on user input.

I'm at the point now where the entire form works as intended and generates the necessary output, ready to transfer to Outlook. I've created the command button, but I need help with the attached macro/VBA coding. I've found some simple tutorials for how to generate an e-mail from Outlook, but they all seem to include a fixed recipient, subject, body text etc., and I need those to be dynamic.

Here's the process I need automated:
1. Select cells B3 to B461 in the output sheet (this range will always be the same; empty rows are automatically hidden)
2. Copy the selection
3. Open Outlook and create a new e-mail
4. Set "From" (if possible) and "BCC" to a fixed e-mail address
5. Retrieve the recipient e-mail address from a specific cell in a hidden sheet
6. Retrieve the CC e-mail addresses from a specific cell in the hidden sheet (they are already stringed together in Outlook format, separated by semicolons)
7. Retrieve the e-mail subject from a specific cell in the hidden sheet
8. Paste the selection into the e-mail body
9. If possible, once pasted, convert the pasted selection from table to text using paragraph marks to separate text

I suppose this should be possible to do, and maybe it's not even that complicated, but it's currently too advanced for me to figure out on my own.

Any help would be greatly appreciated! :)
Viewing all 50271 articles
Browse latest View live


Latest Images