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

Repeat Macro on a series of lines. Help!!!

$
0
0
Hi,
I want to resort data in a matrix array into a string array. To do this I would like to use the sort function in eXcel, but I nee to repeat it for 29000+ lines. This is the macro that I have done to do it:

Code:

Sub Test()
'
' Test Macro
'

'
    Range("B2:P2").Select
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("B2:P2"), _
        SortOn:=xlSortOnCellColor, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange Range("B2:P2")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlLeftToRight
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

I am looking for a way to step this macro to the next line and repeat for the rest of the lines leaving the previous lines in their resorted order. The entire range would be B2:P29169.

I have attached an example of the spreadsheet. When you look at it, What I want to do is have all of the red cells sorted to the right, whilst keeping the data sorted in rows.



Thanks for the help,
Attached Files

Run Time Error 1004 when trying to create a Query Table

$
0
0
Code:

Sub Test()
    Dim strConnect      As String
    Dim strSQL          As String
    Dim Provider        As String
    Dim DataSource      As String
    Dim Extended        As String
   
    Provider = "Microsoft.ACE.OLEDB.12.0"
    DataSource = ThisWorkbook.FullName
    Extended = """Excel 12.0;HDR=YES;"""
    strConnect = "Provider=" & Provider & ";" & _
                "Data Source=" & DataSource & ";" & _
                "Extended Properties=" & Extended & ";"
    strSQL = ThisWorkbook.Names("SQLLetters").RefersToRange.Value
   
    Dim ws              As Worksheet
    Dim dest            As Range
    Dim qt              As QueryTable
   
    Set ws = Sheets("QueryLetters")
    Set dest = ws.Range("A1")
   
    Set qt = ws.ListObjects.Add(SourceType:=xlSrcQuery, Source:=strConnect, Destination:=dest).QueryTable
End Sub

strConnect and dest look correct to me. The destination worksheet is empty.

Any ideas why I get Run-time error '1004': Application-defined or object-defined error???

leave cells empty

$
0
0
Code:

=SUM(IF(Jour1Train=A5,Jour1Abord),IF(Jour2Train=A5,Jour2Abord),IF(Jour3Train=A5,Jour3Abord),IF(Jour4Train=A5,Jour4Abord),IF(Jour5Train=A5,Jour5Abord),,IF(Jour6Train=A5,Jour6Abord))
how to leave the cells that are not used empty blank instead of 0

If No, Hide a row

$
0
0
Hi,

I have three drop down boxes in Cells I have named T_WAN_Provider, T_Managed_Router and T_Managed_Switch.
If user selects "NO" for any of these three cells, "Network_Diagram" cells should be Hidden. Else it shoulf be visible. I tried this code but I have an error for this If statement for usinf OR. If i write If statements seperately, the message apears three times if I select No.

Any help is much appriciated




Code:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rCell As Range

Range("Network_Diagram").EntireRow.Hidden = True

If Range("T_WAN_Provider").Value Or Range("T_Managed_Router").Value Or Range("T_Managed_Switch").Value = "NO" Then
    Range("Network_Diagram").EntireRow.Hidden = False
    MsgBox "Please Attach the Network Diagram! Space has been provided at the bottom of this worksheet"

End If

End Sub

Applying formula only to visible rows.

$
0
0
I have some very complex formulas which I normally apply from the top available row (i.e. row 2) of column to the last row using the following code:

Code:

'Step1
With .Range("CT2:CT" & LastRow)
    .Formula = "=IF(AND(MONTH($W2)=MONTH(EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0)),YEAR($W2)=YEAR(EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0))),((DAY(EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0))+1-DAY($W2))*(($S2/12)/DAY(EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0)))),IF(AND((EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0))>$W2,(EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0))<IF($AB2>=DATE(YEAR($W2)+1,MONTH($W2),DAY($W2)),DATE(YEAR($W2)+1,MONTH($W2),DAY($W2)-1),$AB2),MONTH(EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0))<>MONTH($W2)),(DAY(EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0))*(($S2/12)/DAY(EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0)))),IF(AND(MONTH(IF($AB2>=DATE(YEAR($W2)+1,MONTH($W2),DAY($W2)),DATE(YEAR($W2)+1,MONTH($W2),DAY($W2)-1),$AB2))=MONTH(EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0)),YEAR(IF($AB2>=DATE(YEAR($W2)+1,MONTH($W2),DAY($W2)),DATE(YEAR($W2)+1,MONTH($W2),DAY($W2)-1),$AB2))=YEAR(EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0))),(DAY(IF($AB2>=DATE(YEAR($W2)+1,MONTH($W2),DAY($W2)),DATE(YEAR($W2)+1,MONTH($W2),DAY($W2)-1),$AB2))*(($S2/12)/DAY(EOMONTH(DATEVALUE(RIGHT(CT$1,8)),0)))),0)))"
    .Value = .Value
End With

It works fine, however I would like to do the same for only the visible rows as advanced filtering may be used, I believe I would need such a loop:

Code:

'Step2
For Each rngCell In Range("CT2:CT" & Range("CT2").End(xlDown).Row)
    If Not rngCell.EntireRow.Hidden Then
        FORMULA HERE
        .Value = .Value
    End If
Next rngCell

The problem is that I am unable to convert the formula from step 1 (it is quite complex) to be used in step 2. Is there a method to have the formula from step 1 to be used in step 2?

Thanks a lot.

[SOLVED] Unable to show List of Worksheet from other workbook

$
0
0
Hi,

i am creating a userform where the user can select a particular file and sheet without OPENING the file. see attachments.

this is the code to show all the Excel files that appear in a particular folder

Formula:
Private Sub UserForm_Initialize()

Dim fileList() As String
Dim fName As String
Dim fPath As String
Dim i As Integer
fPath = "\\fploggreena\Contract_Logistics\Finance\Finance\Accounts Rec\ACCOUNT SUMMARIES\Reverse Bill\Coca Cola Amatil\Payment File\*"

fName = Dir(fPath & "*.xls")
While fName <> ""
i = i + 1
ReDim Preserve fileList(1 To i)
fileList(i) = fName
fName = Dir()
Wend
If i = 0 Then
MsgBox "No files found"
Exit Sub
End If
For i = 1 To UBound(fileList)
Me.ListBox1.AddItem fileList(i)
Next i

End Sub



this is the closest that i can get, listing sheets in the active workbook
Formula:
Sub SheetNames()
Columns(1).Insert
For i = 1 To Sheets.Count
Cells(i, 1) = Sheets(i).Name
Next i
End Sub


Can anyone advise how to write a code to list of all the worksheets for the selected Workbook?

Thanks in advance.
Lex
Attached Images

Unable to pop up message

$
0
0
Hi friends,
In this code if the filter entry is not found then the message should pop up 'No match found" so that the user understand that no match found.

Please suggest me a code for it.

Code:

Sub name()
    Dim FilterName As String
        FilterName = InputBox("enter name to filter")
       
        Sheets("Access").Activate
    Range("B7:ab3000").Select
    Range("d7").Select
    AutoFilter = True
    ActiveSheet.Range("$B$7:$Ad$3000").AutoFilter Field:=3, Criteria1:=FilterName, Operator:=xlAnd
    MsgBox "The filtered list is ready!", 64
End Sub

Thanking you in anticipation.

Regards,

Mukesh

Moving Data from one sheet to another.

$
0
0
Hi All!

I am looking to move data from a sheet to another specified sheet that will record the historical data as well as insert a graph to chart trends. The bare bones chart is attached, and would appreciate some assistance in understanding the how's of this.

I am basically fluent in creating and extending calculations and the ability to grab data from another sheet. What I would like is for the 2nd sheet to know that when I enter a new date on the master sheet it is to move te new data to the next row down and record the data. Then I would like the graph to automatically update with the new information to show historical trends...

Any and all help would be greatly appreciated!

Thank you,

EricPOD Leader Weekly Report.xlsx

[HELP]Auto Complete Text from the List

$
0
0
Hi there,

I am a beginner of Macro/VBA or actually I am just using
codes from our experts and applied it in actual. Also this
is my first post in this forum. Please help me out.

I've been using Data Validation-List.
I just want to know if you can make my work easy.
What I want is that if I am going to type in the cell, it will
automatically recommend answer coming from the list.

Thank You Very Much.

An easy one for the gurus. texbox.value into multiple lines of Auto Shape.

$
0
0
Good afternoon,

I have a script where the text from a textbox is put into an autoshape.

I have autofit=true on the shape, which makes the shape stretch to fit the text.

At the moment if the textbox.value is quite long, my autoshape winds up being very wide and short.

I'd like to do something like:

Code:

Shape1.Characters.Text = First X characters of TextBox & vbLf & _
Next X characters of TextBox & vbLf &  _
last X characters of TextBox

If I could get seperate whole words, that would be perfect.

Alternatively, is there a way to fix the width of an AutoShape and autosize the height to fit the text?

Or, is there a way to autofit the text to the box rather than fit the box to the text?

Any assistance you can provide is appreciated.

Set and Dim

$
0
0
What's the difference between dim and set? Examples please.

Task Scheduler Downloading an Empty, Bad File Before Actual File Exists...Not Good

$
0
0
I am trying to download a .csv file from a website each day automatically via Task Scheduler, and subsequently do things with that file automatically. It is supposed to run and download a new file each day of the year. I am not sure when the file comes out but it's typically in the late morning.

Starting to look for the file at 8 AM, Task Scheduler opens/runs a vbs script which opens an Excel workbook automatically, which then downloads the .csv file from a website and formats the data via an Excel module so that it's Access pretty, and then kicks the formatted data into an Access database all automatically. Then it is complete. Rinse and repeat tomorrow.

If I manually kick start this process in the afternoon (choosing a time after the file actually exists on the website)...it runs flawlessly!

But if Task Scheduler starts off looking for the file at 8 AM (or any time before the file exists on the website), it downloads a .csv file full of jibberish computer code...not proper data that I seek. Subsequently it tries to format this garbage file and tries to kick it to Access and Access recognizes nothing so Access doesn't accept anything. This is bad.

My problem is the Task Scheduler THINKS IT WAS SUCCESSFUL...because the process ran...but the file it downloaded although with the correct date in the filename...was a bad, empty file. Therefore the Task Scheduler won't run again until the next day. That is a problem. I need Task Scheduler to keep running every 30 minutes until it gets a good csv file.

I am not a good programmer. A lot of my code was written by someone else but I can read it and manipulate it.

Are there ways out there to work around my problem? How can you tell the Task Scheduler that if the data in the file is bunk to retry again in 30 minutes (which is what it's supposed to do)? Or if Access fails to receive data then to run Task Scheduler again in 30 minutes until Access does receive data? Why does the website allow me to download a file that technically isn't ready yet or doesn't exist yet?

Thank you for any help or suggestions. I hope I explained my problem well. If something doesn't make sense ask me and I will clarify.

Vlook up N/A error

$
0
0
Hello all -
I am attempting to do a Vlookup that has a list box thrown into the mix.

What is happening is inside the list box, there are a group of dates. When I click on a set of dates, a numbers appears in Cell B10 corresponding to how far down from the top I am.

What I am attempting to do is set up a vlookup where the formula inside cell C10 looks at B10, goes to another tab on the spreadsheet called "Date List", looks at the data on "Date List" and fills in C10 with the correct month based on the number in cell B10. But for some reason, I keep getting an "#N/A" error.

I did a Vlook up earlier with no problems. Just can't figure this one out!

Thank you all.

Dave

Dynamic US Map was working fine, but now I'm getting WorksheetFunction.Match 1004 errors

$
0
0
Hello, new to the forum (and to VBA in general).

I'm working on building a tool in Excel that dynamically changes the fill color of each state in a US map, based on values in another sheet. It basically works by finding each state name and value, returning the fill color in the cell one column to the right, and applying that fill color to the appropriate state in the map.

It has been working off and on, but recently broke for no apparent reason. I now receive a 1004 Error (Unable to get the Match property of the WorksheetFunction class).

I have one piece of code (functioning properly) that changes the fill color depending on the value of the cell (which in this case is a percentile):

Code:

Sub ChangeColor()

Dim LastRow As Long
Dim FullRange As Variant
Dim cell As Variant

With ActiveSheet
    LastRow = Range("C" & Rows.Count).End(xlUp).Row
End With

Set FullRange = Range("C2:C" & LastRow)
For Each cell In FullRange

If cell.Value < 0.1 Then cell.Interior.Color = RGB(99, 37, 35)
If cell.Value >= 0.1 And cell.Value < 0.2 Then cell.Interior.Color = RGB(150, 54, 52)
If cell.Value >= 0.2 And cell.Value < 0.3 Then cell.Interior.Color = RGB(218, 150, 148)
If cell.Value >= 0.3 And cell.Value < 0.4 Then cell.Interior.Color = RGB(230, 184, 183)
If cell.Value >= 0.4 And cell.Value < 0.5 Then cell.Interior.Color = RGB(242, 220, 219)
If cell.Value >= 0.5 And cell.Value < 0.6 Then cell.Interior.Color = RGB(235, 241, 222)
If cell.Value >= 0.6 And cell.Value < 0.7 Then cell.Interior.Color = RGB(216, 228, 188)
If cell.Value >= 0.7 And cell.Value < 0.8 Then cell.Interior.Color = RGB(179, 203, 127)
If cell.Value >= 0.8 And cell.Value < 0.9 Then cell.Interior.Color = RGB(118, 147, 60)
If cell.Value >= 0.9 Then cell.Interior.Color = RGB(0, 76, 0)
    Next
End Sub

The second piece of code, which actually populates the colors in the map, looks like this:

Code:

Sub Update_Map_VISITS()

Application.ScreenUpdating = False

    Dim intState As Integer
    Dim strStateName As String
    Dim intStateValue As Variant
    Dim intColorLookup As Variant
    Dim rngStates As Range
    Dim rngColors As Range
   
    Set rngStates = Range(ThisWorkbook.Names("STATES_VISITS").RefersTo)
    Set rngColors = Range(ThisWorkbook.Names("STATE_COLORS_VISITS").RefersTo)
   
        With Worksheets("MainMap")
            For intState = 1 To rngStates.Rows.Count
                strStateName = rngStates.Cells(intState, 1).Text
                intStateValue = rngStates.Cells(intState, 2).Value
                intColorLookup = Application.WorksheetFunction.Match(intStateValue, Range("STATE_COLORS_VISITS"), True)
                    With .Shapes(strStateName)
                        .Fill.Solid
                        .Fill.ForeColor.RGB = rngColors.Cells(intColorLookup, 1).Offset(0, 1).Interior.Color
                    End With
            Next
        End With
   
        Range("E8").Value = Range("C4").Value

Application.ScreenUpdating = True

End Sub

Where STATES_VISITS, and STATE_COLORS_VISITS are named ranges in Excel. I'm getting the error in the following line:

Code:

intColorLookup = Application.WorksheetFunction.Match(intStateValue, Range("STATE_COLORS_VISITS"), True)
I've also attached the full excel file in case that helps. HUGE thank you to anyone who can help shed some light on this!
-Chris
Attached Files

Need Help With Creating Sheets and Compiling Data

$
0
0
I tried creating macros and have wasted valuable time because I am not educated enough to write them. I am in a pinch, can anyone please help? I need to have a list of items, maybe 200 or so, let's say I have a few sheets dedicated to listing these items inside individual cells (or 2 cells that I merge so there is room enough to write the name of the item). So, for example going down the side A1 cell would have typed in it "Widget 1" and A2 would say "Widget 2, and A3 would say "Widget 3, etc and so on. Each time an item is typed into a cell, I'd like a sheet created that is named whatever was typed into the cell, so if A1 had "Widget 1" then a sheet is created that says "Widget 1" (would need to insure that if I typed in Widget 3 in A3 and again in A89, it wouldn't create another sheet named "Widget 3", some error would pop up). These newly created sheets would be a copy of a special sheet that I create, that has fields to fill in with information about the widgets. All widgets need the same sheet, so this is awesome if it is possible. I then want to be able to click a print button that is on the sheet, that prints the sheet; just that sheet.

I do not know the name of all the widgets, they will be a "enter into the list" as they come basis; that is why I need it to create a sheet when the info is typed into the list cells (i don't know the range just yet, im guessing 200, but I can't promise I'll start on "A1" exactly...gonna format a little, add some headers, images, text, fluff, etc).

Any help is greatly appreciated.

Macro based on number which will be different each time.

$
0
0
Hi,

I am very new to the macro scene. I am trying to create a macro based on the following need:

I have a number of spreadsheets, one per client. I will refer to each of these as “spreadsheet 1”.
I have another master spreadsheet, which is a database of all clients, who are listed in column A (“Spreadsheet 2”).
I know how to match the name of the client in spreadsheet 1 to the same client’s name in spreadsheet 2. For the purpose of this illustration, let’s assume that the location of the client’s name in spreadsheet 2 is A45.
I am trying to copy information from Spreadsheet 2 to the Spreadsheet 1 I have open at the time.
The information copied will change location, based on where the client is in the database in spreadsheet 2. For example:

If the client’s name, in spreadsheet 2, is at A45, then, in spreadsheet 1:
A9 = cell B45 from spreadsheet 2;
B9 = cell C45 from spreadsheet 2;
C9 = cell D45 from spreadsheet 2; and so on.

What I have tried doing is having a macro which matches the client name and then returns the number of the cell which contains that client’s name in spreadsheet 2. The macro would then (supposedly):

Convert that number (“x”) to text;
Copy the text,
Create a formula in each cell that is supposed to contain data - in the example above, for example, A9 in spreadsheet 1 – whereby if x = 45, then A9 =B45 from spreadsheet 2, and so on, as above. The formula would be something like “=B45, Spreadsheet 2”.
When creating the formula, the macro would type the letter of the cell reference, and then paste the text. This is where it all went wrong. The macro did not recognize that I was pasting something I had copied before from a cell, and instead treated the pasted number as though I had typed it. Every time I ran the macro thereafter, it was keeping the value of the number from the first time I ran it instead of copying and pasting it from the cell in which the formula had been entered.

The outcome then is that each time I run it I get the same data I got when I first created it, instead of moving to the relevant rows on the source sheet.

I hope this all makes sense – any help would be greatly appreciated. 

Adding Characters and Punctutation to Lookup

$
0
0
I have the below code that returns a value with single quotes. I need to add more characters beyond the single quotes, but am not able to get anything more without an error.

Code:

Sub BandVLook()
Dim LastRow As Long, cell As Range
Dim LookupRange As Range, MyStr As String

Set LookupRange = Sheets("Sheet1").Range("Q2:S500")
LastRow = Sheets("Sheet2").Range("B" & Rows.Count).End(xlUp).Row
With Sheets("Sheet2").Range("D1:D" & LastRow)
    .NumberFormat = "General"
    .FormulaR1C1 = "=""''"" & VLOOKUP(RC[-2],Sheet1!C17:C19,3,FALSE) & ""'"""
    .Value = .Value
End With

End Sub

I am usually able to use the various ascii characters (Chr(xx)) but those aren't working either. Ugh.

The value I'm getting is 'TowerOfPower'.

The value I need is:

("") to ("TowerOfPower")

Thanks for your help!

VBA to Import data or sheets from other workbook

$
0
0
Hi,

I have file1 that has all sheets present in file2. File2 contains the vba code.

I need a VBA code that does following three tasks, separately or combined;

1- If data in any sheet in file2 is changed, it must be updated in relevant sheet in file1.
2- If a new sheet has been added in file2, it must be imported to file1.
3- Only those sheets from file2 must be imported which have a NUMBER as their sheet name. i.e. if sheet name is in text, it must not be imported to file1.

Thank you all

Need to create single list based on data stored in different worksheets, no duplicates

$
0
0
I am using an Excel workbook to collect a series of data. Each worksheet has data specific to a single group. I want to create a single master list based on the data created on each sheet and remove all the duplicates. Automated is best since the end users I am making this document for may not be able to handle dynamically using the Advanced Filter option.

Example Sheet2 A2:A34, Sheet3A2:A34 needs to create a list on Sheet1

[SOLVED] DaysRemaining MsgBox

$
0
0
Greetings,
Open enclosed file and run following macro in order to understand what Macro1 is doing.
Code:

Sub Macro1()
DaysRemaining = Range("AC34") - Date
Select Case DaysRemaining
    Case Is = 1: MsgBox Prompt:="1 days left."
    Case Is = 2: MsgBox Prompt:="2 days left."
    Case Is = 3: MsgBox Prompt:="3 days left."
    Case Is = 4: MsgBox Prompt:="4 days left."
    Case Is = 5: MsgBox Prompt:="5 days left."
    Case Is = 6: MsgBox Prompt:="6 days left."
    Case Is = 7: MsgBox Prompt:="7 days left."
    Case Is = 8: MsgBox Prompt:="8 days left."
    Case Is = 9: MsgBox Prompt:="9 days left."
    Case Is = 10: MsgBox Prompt:="10 days left."
End Select
End Sub

I want to change above macro to below macro.
Red line need to be corrected.
Code:

Sub Macro1()
DaysRemaining = "=MIN(AC2:AC29)" - Date
Select Case DaysRemaining
    Case Is = 1: MsgBox Prompt:="1 days left."
    Case Is = 2: MsgBox Prompt:="2 days left."
    Case Is = 3: MsgBox Prompt:="3 days left."
    Case Is = 4: MsgBox Prompt:="4 days left."
    Case Is = 5: MsgBox Prompt:="5 days left."
    Case Is = 6: MsgBox Prompt:="6 days left."
    Case Is = 7: MsgBox Prompt:="7 days left."
    Case Is = 8: MsgBox Prompt:="8 days left."
    Case Is = 9: MsgBox Prompt:="9 days left."
    Case Is = 10: MsgBox Prompt:="10 days left."
End Select
End Sub

Best regards.
Attached Files
Viewing all 50295 articles
Browse latest View live


Latest Images