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

Referencing UserForm TextBoxes in an array?

$
0
0
Right now, I have three groups consisting of six TextBoxes each on a UserForm. To keep it short, I'll go with one group and call them input1, input2, ..., input6. I have them defined as:
Code:

inputArray = Array(input1.Value, input2.Value, input3.Value, input4.Value, input5.Value, input6.Value)
I want to only accept numeric data, so I've changed non-numeric data to blanks:
Code:

For i = 1 To 6
    If IsNumeric(inputarray(i)) = False Then inputarray(i) = ""
Next i

At this point, I check for any blanks in the array. If there are any when the user clicks OK to populate the sheet with the data, a MsgBox notifies the user that they can either Abort (close the entire form), Retry (go back to the form and fill the blanks), or Ignore (submit the form as-is, with blanks changed to "N/A.")

Abort and Ignore work fine, but I would really like "Retry" to clear the respective textbox. While I could hardcode it with 18 If statements, I would much rather use a For loop like below. I just have no idea how to use the "input," "i," and ".Text" in combination with each other. I know what I have now won't work, but how would I go about naming it?
Code:

For i = 1 To 6
    If IsNumeric(inputarray(i)) = False Then
        inputarray(i) = ""
        Me.inputi.Text = ""
    End If
Next i

Clarification:
I realize I will need to change my initial inputArray to something along the lines of
Code:

For i = 1 To 6
    inputArray(i) = inputi.Value
Next i

But then again, I'm doing a wonderful job of getting it entirely wrong.

AutoFill Met5hod of Range class failed problem

$
0
0
Hello,

I inherited a tool which admittedly I have not yet totally grasped the workings of just yet... It parses data from a .txt file, formats it in a temporary sheet, and then pastes the data into a sheet on the main spreadsheet. The text file contains entries which one or more people do during the day. This tool works just fine if the text file has more than one person performing the work, but if it is just one person, I get the error reported above. When I click Debug, the highlighted line is this:

Selection.AutoFill Destination:=Range("O2:O" & StatCount)

What can I do to make this bug go away?

Here's the entire sub which contains the error:

Code:

Sub AddStats()

    Dim DataCount As Long
    Dim StatCount As Long
    Dim ArtCount As Long
    NextBook.Sheets(1).Activate
    ArtCount = Range("A5").CurrentRegion.Rows.Count
    Range("H1").Select
    ActiveCell.FormulaR1C1 = "CountErrors"
    Range("H2").Select
    ''Logical Test used to determine if error occured
    'ActiveCell.FormulaR1C1 = _
    '  "=--AND(RC[-5]=R[1]C[-5],RC[-4]<>R[1]C[-4],RC[-1]<>R[1]C[-1])"
    ActiveCell.Value = "=--AND(A2=A3,K2=K3,D2<>D3,E2<>E3,G2<>G3)"
    Range("H2").Select
    Selection.AutoFill Destination:=Range("H2:H" & ArtCount)
    Range("K2:K" & ArtCount).Value = "=IFERROR(SUBSTITUTE(TEXT(""'""&C2,""00-00-00""),""-"",""""),C2)"
    Columns("K:K").Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False
    Range("C:C").NumberFormat = "General"
    Range("C2:C" & ArtCount).Value = "=K2"
    Range("H2:H" & ArtCount).Select
    Columns("H:H").Select
    Range("C2:C" & ArtCount).Select
    Columns("C:C").Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Columns("H:H").Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False
    Range("K:K").ClearContents
    DataCount = Range("a2").CurrentRegion.Rows.Count
    Range("E1:E" & DataCount).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range( _
        "N1"), Unique:=True
    Range("N1").Select
    StatCount = Range("N1").CurrentRegion.Rows.Count
    Range("O1").Select
    Sheets(1).Select
    ActiveCell.FormulaR1C1 = "StartTime"
    Range("P1").Select
    ActiveCell.FormulaR1C1 = "EndTime"
    Range("Q1").Select
    ActiveCell.FormulaR1C1 = "CountTime"
    Range("R1").Select
    ActiveCell.FormulaR1C1 = "CompletedTasks"
    Range("S1").Select
    Sheets(1).Select
    ActiveCell.FormulaR1C1 = "Errors"
    Range("T1").Select
    ActiveCell.FormulaR1C1 = "Date"
    Range("T2").Select
    Range("O2").Select
    Selection.FormulaArray = "=MIN(IF(R2C5:R" & ArtCount & "C5=RC14,R2C6:R" & ArtCount & "C6))"
    Range("A2").Select
    Range("O2").Select
    Selection.AutoFill Destination:=Range("O2:O" & StatCount)
    Range("O2:O" & StatCount).Select
    Selection.NumberFormat = "[$-409]h:mm AM/PM;@"
    Range("P2").Select
    Selection.FormulaArray = "=MAX(IF(R2C5:R" & ArtCount & "C5=RC14,R2C6:R" & ArtCount & "C6))"
    Range("P2").Select
    Selection.AutoFill Destination:=Range("P2:P" & StatCount)
    Range("P2:P" & StatCount).Select
    Selection.NumberFormat = "[$-409]h:mm AM/PM;@"
    Range("Q2").Select
    ActiveCell.FormulaR1C1 = "=ROUND(((RC[-1]-RC[-2])*24)*60,0)"
    Range("Q2").Select
    Selection.AutoFill Destination:=Range("Q2:Q" & StatCount)
    Range("Q2:Q" & StatCount).Select
    Range("Q1").Select
    ActiveCell.FormulaR1C1 = "TotalCountTime(mins)"
    Range("R2").Select
    ActiveCell.FormulaR1C1 = "=COUNTIF(R2C5:R" & ArtCount & "C5,RC14)"
    Range("R2").Select
    Selection.AutoFill Destination:=Range("R2:R" & StatCount)
    Range("R2:R" & StatCount).Select
    Range("S2").Select
    ActiveCell.FormulaR1C1 = "=SUMIF(R2C5:R" & ArtCount & "C5,RC14,R2C8:R" & ArtCount & "C8)" ' Needs Variable
    Range("S3").Select
    Range("S2").Select
    Selection.AutoFill Destination:=Range("S2:S" & StatCount)
    Range("S2:S" & StatCount).Select
    Range("T2").Select
    ActiveCell.FormulaR1C1 = "=TODAY()"
    Range("T2").Select
    Selection.AutoFill Destination:=Range("T2:T" & StatCount)
    Range("T2:T" & StatCount).Select
    Columns("N:T").Select
    Selection.Copy
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False
    Columns("C:C").Select
    With Selection
        .HorizontalAlignment = xlRight
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    'Selection.NumberFormat = "00-00-00"
    Range("O1:T1").Select
    Selection.Font.Bold = True
    Columns("N:T").Select
    Columns("N:T").EntireColumn.AutoFit
    Range("N1").Select
    Range("H1").Font.Bold = True
    Columns("H:H").EntireColumn.AutoFit
    Range("U1").Value = "Week"
    Range("U2:U" & StatCount).Value = "=Weeknum(Today())"
    Range("U:U").Copy
    Range("U1").PasteSpecial xlPasteValues
    Application.CutCopyMode = False
   
   
End Sub

Can someone tell me by this autofill code gives me a run error.

$
0
0
Update_Row_Count and Update_Row_Count2 are variables. I want to autofill A100:G1000 . I'm just using variables instead of numbers.

Selection.AutoFill Destination:=Range("A" & Update_Row_Count & ":G" & Update_Row_Count2)

Merge cells in corresponding column based on similar values

$
0
0
Hello Everybody,
I would like to merge cells in different columns based on similar values in column "FN".
The attachment shows you how the result should look like.
Thank you very much for your support.
Niclal
Attached Files

Excel does not recognize format of pasted Word file

$
0
0
I am trying to use Excel to remap some text in a word file to generate a file formatted for an online education tool. The text from Word is a series of multiple choice questions and answers. The correct answer letter in the Word file is formatted as Bold and Underlined. Therefore after pasting into Excel I wanted to change the correct letter to the word “Correct” I was hoping to move through the answer letters and test if they were Bold or not. When I found the Bold letter I would replace it with the word “Correct” After that Excel formulas would finish the remapping.

I ran into a problem when Excel VBA would not see the correct answer as Bold. This is described below.

Screenshot showing cell B17 formatted as Bold, Underlined. Note the highlighted buttons on the menu bar indicating this is the case.

Name: Presentation1.jpg Views: 0 Size: 39.8 KB


However if I click on the Font menu you can see that the format is essentially null

Name: Presentation2.jpg Views: 0 Size: 44.9 KB

I am trying to use the following code to insert the word “Correct” in the cells with a Bold font. I cannot get VBA to recognize the font contained in cell B17 as Bold. The other cells B13, B15, B19 and B21 show up as a Regular font. It is only cell B17 that seems to have problems, even though visually it appears to be Bold and Underlined. I tried getting the code to recognize the font as “not regular” but it does not recognize that either. It seems that the font information is null or non-existent. I am not sure how to proceed that this point. It seems to be a bug in either the Excel copy/paste or the way Excel stores font information. It seems the menu bar has the right information, but the Font menu does not. Either way VBA is not able to access the information. Below is the code I am trying to use.

Sub IsBold()
START:
For jump = 1 To 5

'If ActiveCell.Font.Bold = True Then (I was trying this, when it didn’t work I tried the line below)
If ActiveCell.Font.FontStyle <> "Regular" Then (this didn’t work either)
ActiveCell.Value = "Correct"
End If

ActiveCell.Select
Selection.End(xlDown).Select

Next jump

Selection.End(xlDown).Select

GoTo START:

End Sub
Attached Images

Color cells by cumulative sum

$
0
0
Hi, i want to color a column according to cummulative sum of next column, is there any way to make it with a macro. i thing attachment will be more clear.

thanks,

sample_sum.xls

VB code to change the font to white for selected range

$
0
0
Hello:

Please refer to attached file.

i have data range in cell A2 to B14.
I also have check box in cell C2 to C14.

I need a VB code to change the font to white for the range in column A AND B if they have corresponding check box
marked in column C.

For example :

If the box in cell C2 and C4 is marked then the corresponding range in column A and B.

Let me know if you have any questions.
Thanks.


Riz
Attached Files

Multiple Pivot report filter - based on another pivot on another worksheet

$
0
0
Hi Can anyone be of assistance?

On 1 worksheet ("Market Data") I have a pivot table that has report filter that gets updated by a slicer on the main reporting sheet.

On another worksheet ("DG Data") I have another pivot table (using separate data source), which updates its report filter to the same selection, using the following code (code in "Market Data" worksheet).:

Code:

Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)

Application.ScreenUpdating = False
On Error Resume Next

Sheets("Market Data"). Select
Set rng = Sheets("Market Data").Range("D3")    ''' this cell just references the value in the report filter that I have selected on the slicer, eg "Apple", etc

If Not Application.Intersect(Target, rng) Is Nothing Then
  Sheets("DG Pivot").Select
        With Sheets("DG Pivot").PivotTables("PivotTable1").PivotFields("New Product Type")
            .ClearAllFilters
            If Len(rng.Value) > 0 Then .CurrentPage = rng.Value
        End With
End If

Application.ScreenUpdating = True
End Sub

This works fine.
However it does not let me select multiple values from the slicer (ie, it references "Multiple items" on the original pivot, and as it cannot select that as a value on the 2nd pivot, it just leaved the field unfiltered).

Is there a way I can get the pivot table on the "DG Pivot" worksheet to replicate the filter selection (when multiple chosen) on the Market data worksheet?

Any help is most appreciated. Thanks

create a macro that turns cells red 10 days after initial data was added to the cell

$
0
0
Hi everyone,

I hope someone can help with this... I have a schedule where people enter data into a different columns called "motions" which are spread out through the chart. When data is put into the motion chart I have set it up so that the corresponding cell in the column to the right show the date that data was entered.

What I need to do now is set up a macro, which turns the cells in the "motions" column red 10 ****business days**** after the data was initially entered *AND* to delete the data and cells 11 ****business days**** after the initial entry date.

Any help would be very appreciated! Thank you!

Here is what I have so far:

Code:

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    Dim rCell As Range
    Dim rChange As Range
   
    On Error GoTo ErrHandler
    Set rChange = Intersect(Target, Range("C8:C67, F8:F67, I8:I67, L8:L67, O8:O67, R8:R67, U8:U67, X8:X67, AA8:AA67, AD8:AD67, AG8:AG67, AJ8:AJ67, AL8:AL67, AO8:AO67, AR8:AR67, AU8:AU67, AX8:AX67, AZ8:AZ67, BC8:BC67, BF8:BF67"))
    If Not rChange Is Nothing Then
        Application.EnableEvents = False
        For Each rCell In rChange
            If rCell > "" Then
                With rCell.Offset(0, 1)
                    .Value = Now
                    .NumberFormat = "dd-mmm"
                End With
            Else
                rCell.Offset(0, 1).ClearContents
            End If
        Next
    End If

ExitHandler:
    Set rCell = Nothing
    Set rChange = Nothing
    Application.EnableEvents = True
    Exit Sub
ErrHandler:
    MsgBox Err.Description
    Resume ExitHandler
End Sub

Sub Colouring()
Dim cell As Range
    For Each cell In Range("D8:D67, G8:G67, J8:J67, M8:M67, P8:P67, S8:S67, V8:V67, Y8:Y67, AB8:AB67, AE8:AE67, AH8:AH67, AK8:AK67, AM8:AM67, AP8:AP67, AS8:AS67, AV8:AV67, AY8:AY67, BA8:BA67, BD8:BD67, BG8:BG67")
        If cell.Value > Date + 10 Then
            cell.Interior.ColorIndex = 6
        End If
 
Next cell
End Sub

How to replace a sheet that has formulas linked to it, without REF-errors?

$
0
0
Hi! The issue is the following:
I have a workbook with several sheets. One of them contains a central table with data, "Depoes". On several other sheets I have formulas that is connected to the sheet "Depoes".
What I am trying is to do, with VBA, is to DELETE the sheet "Depoes", and then replace it with a NEW copy, from "THE MASTER WORKBOOK", where the sheet "DEPOES" is updated.

The sheet removal, and retreival of a new copy is working fine. The issue is the formulas, they don't like it, when the sheet "Depoes" is deleted, so I get "REF-errors".

I tried to replace the "Equal sign" in the formulas with the "fool-proof-code" of "ZZZXZZZ", before doing the deletion and retreival of the new copy, but using REPLACE in VBA, after that, replacing
"ZZZXZZZ" with "=" will NOT work......probably since I am trying to create a formula out of a string......

Anybody has any ideas?

Best Regards from Sweden
Björn

Opening Notepad a saved notepad file and copying the data on it

$
0
0
Hi,

I'm trying to merge edit 2 types of codes...

1. That Opens a notepad file
2. Copies the Data and automatically closes out notepad

Part 2 works if your sending data from an excel sheet to the notepad but I need it to work from oepning a notepadfile directly.

For some reason,

The File will open with no issue but the data on the notepad won't copy.
(I want it to copy (Highlight) blue so after the notepad automatically closes, I can just paste the data to it's destination.


here is the code...


Code:

Dim Shex As Object
Set Shex = CreateObject("Shell.Application")
tgtfile = "C:\Folder Location Goes Here"
Shex.Open (tgtfile)


''Start Notepad And let it recieve focus
'    Shell "notepad.exe", vbNormalFocus

'Send the keys CTRL+V To Notepad (i.e the window that has focus)
'    SendKeys "^V"
'
'Copy whats on the Clipboard
SendKeys "^a"
SendKeys "^c"

   
waitTime = TimeSerial(Hour(Now()), Minute(Now()), Second(Now()) + 10)
Application.Wait waitTime
   
Application.SendKeys "%{F4}", True
Application.SendKeys "{TAB}", True
Application.SendKeys "{ENTER}", True


'End Sub
       
End Sub


Please Help

Cancel button causes error and vb editor to open

$
0
0
I have an input box that pops up in my workbook but if I hit the cancel button it sends me directly to the VB editor and highlights where the Macro Stopped.

Can i have it so that the page goes back to normal AFTER a message box pops up that reads
"You are canceling the process'

Any Help would be greatly aprreciated.

Comparison Macro-Table Values

$
0
0
First, thanks in advance..
I believe the task is not that easy but it would be great to have it done, as the manual work takes ages to be finished. You will find the workbook in the attached files. It does contain the real data but I cut it down to few lines. I also emptied the columns, which we don't need but in a real workbook they do contain data.
As I have mentioned in the thread, info in Sheet1 is what filled in by the company and is missing the info, which appears in Sheet2, which is sent by supplier. On the last sheet Final I included how these columns generally look when it is done manually, that sheet represents Sheet1 after info from Sheet2 is checked and copied to the representative cells. I do not care how Sheet2 will look in the end.
In addition to what I described in the thread, I forgot to mention that it would be nice to color the rows with products, which didn't appear on Sheet1 before copying.
Below you have description of what I need from the forum:

1) Compare products from column B (starting from B3 to last row) from Sheet2 to column D (also from D3 to last row) from Sheet 1.
- in the workbook you will see that Sheet1 is missing 2 products
2) If products from Sheet2 do appear on Sheet1, then copy cells from Sheet2:
1. Cell from column C from Sheet2 to column C in Sheet1 (let's say it is the first product, so Sheet2.C4 to Sheet1.C4) (these are the columns with heading Number - if this can help...)
- this info generally appears on the Sheet1, so it should be either checked (same as product number) or just copied from Sheet2, we have instances when info is different, that is why it would be nice if excel could alert me if value is different
2. Sheet2.I4 to Sheet1.M4 (Columns called Weight2)
- Sheet2 contains only one column Weight, which should be copied to column Weight2 on the first sheet
3. Sheet2.L4 to Sheet1.O4 (Columns called Delivery date)
3) Calculate the difference between columns (column L- column M) in the column N.
4) Not very important, but would be great if Excel alerted if he changes any cell that already had data inserted. So in case Excel copies info from Sheet2 to the blank cell or it contains exactly same info - then it is ok, but if value was different - then highlight cell in red.
5) Lastly, for those products, which did not appear on Sheet1, copy info to the last to the next empty row on Sheet1: Sheet2.B to Sheet1.D, Sheet2.C to Sheet1.C, Sheet2.I to Sheet1.M, Sheet2.L to Sheet1.O (basically all the same as before, just fill it up from supplier's list to company's list)

In the sheet with 7 products that is not the problem, but the actual spreadsheet contains thousands of entries. The combination of numbers used in Product column is not unique, so it might appear several times before. What makes it unique is the combination of 2 values: that combination and code to the left of it starting with EX/ EF in that case. So in case macro simply copies info once it found the match, it will keep overwriting the old entries... and anyway checking the entire table for each entry is quite a heavy task. The entries in Sheet2 are always up-to-date, might include info from 2-3 days period, max. 40 entries but is there anyway to prevent macro from checking the entire table in Sheet1? Maybe based on the date, let’s say, filter it by the date we sent the product or maybe check only those rows, where delivery date is missing


Lax
Attached Files

how to: user input form to select a range to be used as the array elements(?) in function?

$
0
0
Hi all, basically I've got 3 bits of code that i'm trying to stitch together and am only 1/2 way through my VBA for Dummies book... :)

What i'm trying to do is create an input form that appears with 2 options. Based on the option selected, one of 2 ranges will be identified and passed through to a function procedure as the input array.... after the function runs, I would like it's results (another array) to be passed through as the elements or variables(?) for another array in the sub procedure...

I have never used input forms before so i'm kind of lost right off the bat and i'm only really just starting to understand what my macro recorder's been doing for me all these years! :)

Currently I have a macro that creates what you see in the attached sample workbook... I would at this point run the code in Step 3 below, but I would like to modify by adding Setp 1 and 2 below at this point...

Step 1- User input... I have no idea how this is supposed to go, but I would like "OptionModelType" to select Range(=LEFT(B30:End(xlToRight),3) ie. In the last part of code below (Step 3) the code enters the first 3 characters of cell30 into cell1 for each column... if I do this first, then the desired range would be B1:B last column, obviously if the user input box is going to work here I will have to move that process to have already occurred before this point unless the range can be determined without this step at all? OptionModelName is basically the same range except for the full value in row 30 and not just the first 3 characters.

Code:


'No Idea What I'm supposed to do here...'

Private Sub GoButton1_Click()

End Sub

Private Sub OptionModelType_Click()

End Sub

Private Sub OptionModelName_Click()

End Sub

Private Sub UserForm_Click()

End Sub

once the user has made a selection and clicked "Go", I would like the selected range to be used as the input array in this function... By the way, this function has an optional count operation that I don't need, i'm just not 100% sure which code an can delete without messing it up, so I would like to have Count set to False automatically all the time.

Step 2- The UniqueItems Function

Code:

Option Base 1

Function UniqueItems(ArrayIn, Optional Count As Variant) As Variant
'  Accepts an array or range as input
'  If Count = True or is missing, the function returns the number of unique elements
'  If Count = False, the function returns a variant array of unique elements
    Dim Unique() As Variant ' array that holds the unique items
    Dim Element As Variant
    Dim i As Integer
    Dim FoundMatch As Boolean
'  If 2nd argument is missing, assign default value
    If IsMissing(Count) Then Count = True
'  Counter for number of unique elements
    NumUnique = 0
'  Loop thru the input array
    For Each Element In ArrayIn
        FoundMatch = False
'      Has item been added yet?
        For i = 1 To NumUnique
            If Element = Unique(i) Then
                FoundMatch = True
                Exit For '(exit loop)
            End If
        Next i
AddItem:
'      If not in list, add the item to unique list
        If Not FoundMatch And Not IsEmpty(Element) Then
            NumUnique = NumUnique + 1
            ReDim Preserve Unique(NumUnique)
            Unique(NumUnique) = Element
        End If
    Next Element
'  Assign a value to the function
    If Count Then UniqueItems = NumUnique Else UniqueItems = Unique
End Function

Finally this function produces a list of all the unique values in the input array, but rather than having them copied into cells, (unless that's a necessary step...) I would like this list of values to be passed through as the array elements for VArray in this next bit... ie. VArray = Array("results from this function" instead of the hard keyed variables in the code below)

Step 3- The rest... FYI I also don't want to delete any worksheets, but for some reason the code doesn't seem to delete them anyway... again, have been hesitant to remove any lines as the code still functions as is :)

Code:

Sub sSplitData()

Dim wsOriginal As Worksheet
Dim ws As Worksheet
Dim wsMaster As Worksheet
Dim lLC As Long, i As Long
Dim vElement, vArray
vArray = Array("IND", "OFF", "RET") ' Trying to get these elements input from previous function'
Dim rDelete As Range

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
On Error Resume Next

Set wsOriginal = Sheets("Sheet3")

' delete all worksheets first (except the original)
For Each ws In ThisWorkbook.Sheets
    Application.DisplayAlerts = False
    If ws.Name <> wsOriginal.Name Then
        ws.Delete
    End If
    Application.DisplayAlerts = True
Next 'ws

' make a copy of the original and name it "Master"
wsOriginal.Copy after:=Sheets(Sheets.Count)
Set wsMaster = ActiveSheet
wsMaster.Name = "Master"

' add column headings to "Master" worksheet...................... ' will need to move this earlier to before input form unless range can be determined without physically adding these values to row 1???'
With wsMaster
    lLC = .Cells(4, .Columns.Count).End(xlToLeft).Column
    For i = 2 To lLC
        .Cells(1, i).Value = _
            Left(.Cells(30, i).Value, 3)
    Next 'i
End With

' copy Master worksheet to individual sheets
Application.DisplayAlerts = False
For Each vElement In vArray
    wsMaster.Copy after:=Sheets(Sheets.Count)
    Set ws = ActiveSheet
    ws.Name = vElement
Next 'vElement
Application.DisplayAlerts = True

' delete Master worksheet
Application.DisplayAlerts = False
'wsMaster.Delete
Application.DisplayAlerts = True

' delete columns on each sheet
For Each vElement In vArray
    Set ws = Sheets(vElement)
    With ws
        lLC = .Cells(1, .Columns.Count).End(xlToLeft).Column
        For i = 2 To lLC
            If .Cells(1, i).Value <> vElement Then
                If rDelete Is Nothing Then
                    Set rDelete = .Cells(1, i)
                Else
                    Set rDelete = Union(rDelete, .Cells(1, i))
                End If
            End If
        Next 'i
        If Not rDelete Is Nothing Then
            rDelete.EntireColumn.Delete
        End If
        Set rDelete = Nothing
    End With
Next 'vElement

' tidy up
On Error GoTo 0
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub

I have attached a sample worksheet and any help would be very much appreciated! Also, in the original workbook, many of the values have formulas and vlookups, but in order to keep this small and simple I've just included values and formats in this sample...sample3.xlsm

Thanks,
Joe

VBA Function to Loop Through Filtered Range

$
0
0
This is my first post. Please let me know if I do not meet all of the posting requirements. THX

I require a VBA function that will loop through a filtered range and perform calculations incrementally on visible rows. I tried starting with a simple count of the filtered results but will need to do more advanced calculations like a weighted average of margins. I was able to make a Sub that worked just fine but when I tried making a function instead it didn't work anymore and just keeps returning the total number of rows in the range instead of the total number of cells in the visible range. I have tried a non VBA approach but the calculation slowed down the workbook terribly.

Can anyone think of a reason that a function would fail on a filtered range?
Here is the code that I tried.
Code:

Function VisibleRows(rng As Range) As Integer
    Dim cl As Range
    Dim count As Integer
   
    For Each cl In rng.SpecialCells(xlCellTypeVisible)
        Debug.Print cl
        VisibleRows = VisibleRows + 1
    Next cl
End Function

Here is the code(template) I started with. This worked but is not a function.
Code:

Sub VisibleRowsCount()
    Dim rng As Range
    Dim cl As Range
    Dim count As Integer
   
    Set rng = Range("B4:B11")
    For Each cl In rng.SpecialCells(xlCellTypeVisible)
        Debug.Print cl
        count = count + 1
    Next cl
End Sub


VBA that Creates a tab for each unique set of data and moves it over

$
0
0
Hello,

I have a set of data similar to the below (header is in row 2, columns A:G):

Vendor#|Vendor Name|City|State|Item#|Item Name|Price|
1223|Bobs Produce|New York|NY|14456|Potatoes|$5.42
1225|Pops Produce|New York|NY|142|Potatoes|$5.03

I have tried a couple of cut/copy codes, which do a good job of moving data into an already created sheet, but I am looking for something that can create a tab for each vendor number contained in the data (named the vendor number) and move (or copy) all line items with that vendor number into the new sheet. Header information will also need to be included in the new sheet. There can be 3-20 different vendors in a list of data.

Is there a VBA code that can do this?

Robocopy not working

$
0
0
Hello,

I'm trying to use Robocopy on a directory but it doesn't seem to be working. I haven't had much practice with this command so I'm at a bit of a loss here.

I can get the command to successfully work on a local drive (without spaces) but when it comes to a server environment it comes up empty. I am wondering if it is because the path has spaces in the directory?
If that is the case how would I go about removing the spaces but still getting the path to work with Robocopy.

Any advice is greatly appreciated!




Code:

Sub INSP_RoboDrwing()
Dim fSource As String
Dim fDest As String
Dim fname As String


        Dim I      As Integer

   
   
        spath = "C:\Users\Jason\Desktop\BotRun\Bot1"
        fDest = "C:\Users\Jason\Desktop\BotRun\Bot2\"
        strFullPath = "R:\_QMS In-Work_\ECNs In-Work\ECN 199 (Hydrowave Saltwater) HOLD\100038000000 rev L\100038000000.SLDDRW"
   
                ' Seperate File from directory.
                For I = Len(strFullPath) To 1 Step -1
                    If Mid(strFullPath, I, 1) = "\" Then
                        FileNameFromPath = Right(strFullPath, Len(strFullPath) - I)
                        Exit For
                    End If
                Next
       
       
                ' Seperate Directory from file.
                For I = Len(strFullPath) To 1 Step -1
                    If Mid(strFullPath, I, 1) = "\" Then
                        FolderFromPath = Left(strFullPath, I)
                        Exit For
                    End If
                Next

        fSource = FolderFromPath
        fname = FileNameFromPath

Shell "cmd /k robocopy " & FolderFromPath & " " & fDest & " " & FileNameFromPath
End Sub

The workbook closes, but the excel application remains open

$
0
0
Hello,

I have an application that requires a login, if the person decides to not login they can click the cancel button to close out the application. The problem is, the application is prompting for a save, save as, cancel, even though the person didnt login in the first place to make chnages to save. I just want the application to force close without the prompt. I have the following code so far:

Code:

Private Sub Image2_Click()
Application.Quit
'Application.DisplayAlerts = False
    'ActiveWorkbook.Close
    'Application.DisplayAlerts = True
ThisWorkbook.Saved = True
ActiveWorkbook.Close savechanges:=False
'Application.Quit
End Sub

Regardless of how i try to manipulate this code, the only result i am getting is the workbook closing but the excel application remains open and i have to click the X in the top right corner to close the excel application. So its as if i have to close it twice. Can someone help me with closing the entire application without prompt.

Checking for a label between two other labels and conditionally copy/pasting

$
0
0
I have a column (call it A) in Excel lists off different items and their properties. Every item has the word "Type" associated with it and so there is a cell with that label in column A so that in the column beside it (B) the type can be listed. Some (not all) items also have a "Widget" label associated with them.

Since each item only has one "Type" label I would like to be able to do is have Excel search for the "Type" label and then check whether there is a "Widget" label BEFORE the next "Type" label, and if there is paste the value in column B adjacent to the "Type" label in another sheet. It would continue doing this until no more instances of the word "Type" were found. Is this something that's feasible to implement? To make the layout more clear a sample column is below. Note that the number of spaces between each entry, unfortunately, is not consistent and so cannot be used as a way to track where one is.


**Type** 01
Width .5
Length .4
Height .3
Weight 15
Widget Blue
**Type** 072
Width .1
Length .1
Height .1
Weight 50
**Type** 025
Width .4
Length .4
Height .4
Weight 11
Widget Red

Trying to find a substring in a list of words

$
0
0
Dear all,

I am new here and would be very glad to receive your responses with regard to my (urgent) question:

I have a list of about 30,000 filenames in column A and I would like to group these names in another column according to this "method": In one cell (let's say C1), I would tell Excel that it should look for all names which contain the same substring of 8 characters. I would then set a second "filter" by telling Excel in cell C2 that I only want groups of at least 10 entries.

For example, if I put "10" in C1 and "100" in C2, I would get a list with all names containing the same substring with 10 characters and which appear at least 100 times in the list (for example: "Newsletter" would be the substring found, appearing in 100 names and another group would be "sideletter" appearing 145 times).

Is this possible with a function or with VBA?

Thanks a lot for your help!!

Best,
Fin
Viewing all 49934 articles
Browse latest View live