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

[SOLVED] Date Format Error in VBA

$
0
0
Hello,

I want to convert the date values in Column("B") of a .csv file to the format "YYYYMMDD"

I tried the below code but after running the code the values are still showing in Original format only ( i.e 25-03-2020)

Code:

Sub Practice()
Dim LR As Long
LR = Range("A" & Rows.Count).End(xlUp).Row
    Range("B1:B" & LR).NumberFormat = "yyyymmdd"

End Sub

But when I manually add +0 to any of the values in Column(B) in other column say Column("G")then it is showing correct format in "YYYYMMDD" format

Can anyone guide me.

Thank you

Referencing an Absolute Value Cell in VBA

$
0
0
Hello everyone. I am having trouble referencing a cell (with changing values) in my code. I tried putting in the Cell reference and then the coordinates of the cell, but that didn't work. I need the cell as it is part of an equation. I have posted a pic below of my issue.

As you can see my current work around is by defining the values with the current rates, but the rates will change multiple time so that will eventually not work. I need it to simply reference the cell and said value instead of a single numerical value. The cells that need to be referred do have titles (the ones to the left of them) if that helps/affects anything.



VBAHelp.PNG




I apologize if I am not being completely clear, but please let me know if you need any additional information. Thank you sooo much.

Using For Each .. Next to Define Array Contents

$
0
0
Hello all-

I am using the attached code to collapse and expand excel sheets based on their title. It works great. However, I have to define the array members contents exactly as the sheets are named. If there is an error in my typing etc I get an Excel error (Subscript out of Range Error 9). Of course this is easy to fix, but now I'm thinking about adaptability as I add/subtract sheets or change their names. The MSFT help suggested that I use For Each/Next to define the array collection members vs how I am doing it. Honestly, I have no idea how to convert this code to that method so I'm looking for help.

Thanks
Rob
Attached Files

Offsets duplicates and text file

$
0
0
Hello,

First of all I am not quite sure how to use the Input.xlsx workbook and Sheet1 from it without inputting it in the VBA.
I was thinking of ActiveWorkbook and ActiveSheet, I think it might work, though the code is ran from Code.xlsm

The code has multiple functionalities than have to be tweaked

1) It Deletes the Rows where there are duplicates. This is a bit wrong, as I would have wanted to make it delete the rows if it finds duplicates on columns A&C.

Such as scanning columns A&C and
Code:

If (duplicates are found on both columns A&C) Then delete duplicated row, where it has 2 incidences of duplicate values found on columns A&C.
So far, it deletes the entire row if at least 1 duplicate cell is found on columns A:F

2) It is trying to look for a keyword and based on the results it should copy the offsets in the Input.xlsx file on Sheet1, columns G H I J K (the keyword should not be case sensitive).

The problem is that it stops after the first result is encountered and if I expand the range of the Offset.Value result, it keeps pasting the same value everywhere.

3) After 1) and 2) are done it should copy the values from cells E F G in a .txt file with the output similar to the one found in attachments.

Code:

Key:
Code.xlsm is where the code will  ran from
Input.xlsx is the input file (input values on A:F), but will also serve as output for 1) and 2) columns G:K on Sheet1
Test.txt is the output file for 3)

Thank you very much in advance, it is appreciated.

Below, I am also attaching the code from the Code.xlsm file

Code:

Public Sub Test()

Workbooks("Input.xlsx").Worksheets("Sheet1").Range("A:D").RemoveDuplicates Columns:=1, Header:=xlNo

Dim SrchRng As Range, cel11 As Range
Set SrchRng = Workbooks("Input.xlsx").Worksheets("Sheet1").Range("F2:F9999")
For Each cel11 In SrchRng
    If InStr(cel11.Value, "nice") > 0 Then
 Workbooks("Input.xlsx").Worksheets("Sheet1").Range("G2").Value = cel11.Offset(0, -5).Value
 Workbooks("Input.xlsx").Worksheets("Sheet1").Range("H2").Value = cel11.Offset(0, -4).Value
 Workbooks("Input.xlsx").Worksheets("Sheet1").Range("I2").Value = cel11.Offset(0, -3).Value
 Workbooks("Input.xlsx").Worksheets("Sheet1").Range("J2").Value = cel11.Offset(0, -2).Value
 Workbooks("Input.xlsx").Worksheets("Sheet1").Range("K2").Value = cel11.Offset(0, -1).Value
    End If
Next cel11

        Open ThisWorkbook.Path & "/Test.txt" For Output As #1
            Print #1, "*Book Name"; Column_G_Value; "*";
            Print #1, "*", Column_H_value, column_I_value, column_J_value, column_K_value; "*";

End Sub

Sheet1 is identical with the below 2 pictures but it has the values input from columns A:F. Everything else from G:K is the output that should be generated by the code as for 1) and 2)

Sheets Expected Answer and Another possible answer within Input.xlsx represent the possible outcome when the code is running tasks 1) and2) as above, and they are just for observation and nothing more.

The only difference between those 2 Sheets is that the former one outputs the offsets near the keyword, whereas the latter outputs the results from Row2 onwards )
I made 2 possible outcome Sheets as I'm not sure which one would be easier to use as an example while creating the code.
Capture.JPG
Capture2.JPG

Finally, I am also attaching the output .txt file that could be generated by the code for 3)

Best wishes
Gordon
Attached Files

userform previous record

$
0
0
Hi,
I have two userforms..
in the first userform, i am trying to update previous record.. so when i click previous, the lastrow in the sheet must be populated.
But i have a combobox in the form and change event.. this makes when the previous value updated , closes the userform..
When i comment out combobox value to be taken from sheet, then it works fine..
is there any alternative.

Web scraping - check if filter list is expanded or collapsed

$
0
0
This is the code for the element I want to target by navigating in internet explorer medium:

HTML Code:

    div id="docTypeForm:filterPnl" class="rf-cp rf-tgp" style="margin-bottom: 10px;"
        input id="docTypeForm:filterPnl-value" name="docTypeForm:filterPnl-value" type="hidden" value="true"

Document Store - Google Chrome 25_03_2020 20_06_39.png

I am running macro that navigates to and enters values inside the textboxes. The problem is I can only run the macro once because the filter is default collapsed. So my first step in the macro is to click the arrows and expand the filter. If I run the macro a second time, the filter will still be expanded so it goes in error because it collapse the filter when clicking. Is there a way to check first what the condition of the div is?

I`m able to return the text inside the class and style in the first line but not 1 text from the second line.

Below a few examples that I`ve tried(sorry if it is messy):

HTML Code:


'Set check = obJIE.document.getElementById("docTypeForm:filterPnl-Value")

'If check.Value = False Then


'MsgBox obJIE.document.getElementByValue("docTypeForm:filterPnl").getAttribute("class")

 'MsgBox check

'If obJIE.document.getElementById("docTypeForm:filterPnl-Value").isVisible = False Then
'        MsgBox False
'Else
'MsgBox True '

'End If

Code works with Sub but get an error with Private Sub

Data Validation- Formula Automatically Shifting Referenced Column

$
0
0
Greetings!

Backstory:So I made this workbook to make it easier for Supply Chain of our hospital to process all items used in a patient's hospital case by making an excel sheet with an interactive page vs what was used previously (see the tab "Data"). I managed to convert what they currently use to a more user friendly format, "SSID INFO."


The Issue: the data validation formula for cell B5 changes every time you move tabs. It changes the formula range to reference the next column when you return back to the tab. The result is that it goes from from CASE #[X]-[LOG No.] to [corresponding number]. (e.g Case #1-906306 -> 1). I am unsure what exactly is causing this to happen. Unfortunately, my knowledge in data validation is limited to having people fill out forms, referencing data from a static range, and not extending beyond one tab.


How It Works: For simplicity, I removed the macro that converts the raw extracted data and pastes it appropriately into the tab, "DATA." I also removed the macro to refresh the pivot tables. In tab, "SSID INFO," I have a pivot table that starts in cell S1 that references info in the tab, "DATA." Column T references the numerical order next to the pivot table. Cell U1 has a vlookup that references which case number the sheet is currently referencing. Cell V1 has the max of range, $T:$T.

The data validation is in Cell B5. All the vlookups and the pivot table in Q19 are powered by what appears in cell b5. The pivot table's filter matches whatever is in cell B5. Data validation is referencing the entire column and is using offset to remove blank cells, since the pivot table is dynamic due to more information being added throughout the month.

The data tab: the info below the purple header is automatically generated (entered fake data), the black header was added by me for reference purposes, and the blue references an external report (formulas have been removed to avoid external reference error).

VBA: 1) cmd_nxt (SSID INFO) - allows the buttons to select the next case or go back to the previous case. (See "PREVIOUS" & "NEXT")
2) module 1 - creates the function removenumbers
3) module 2 - creates the function no_brackets
4) This worbook - Automatically changes the filter for the pivot table in Q19 to match Cell B5.


Any assistance would be greatly appreciated!
Attached Files

pausing and starting a Macro

$
0
0
Hi I have a spreadsheet that I am creating that has 12 tabs. I have created a macro VBA code to automatically scroll through the tabs at a set amount of time in an infinite loop. I was wondering if there was a way to put a button in each tab that will allow me to pause and start the Macro of going through the screens. I need to be able to pause the screen so I can manually input information.

Here is my tab switching code I have.

Code:

Sub SwitchSheets()
    Application.WindowState = xlMaximized
    ActiveWindow.WindowState = xlMaximized
    Application.DisplayFullScreen = True
   
    Dim i As Integer
    Dim Pause As Double
   
    Pause = 15 'Pause delay in Seconds
    Loops = 2  'How many loops do you want to do
   
        For J = 1 To Loops
        For i = 1 To 12
       
        Worksheets(i).Select 'Select the next worksheet
        x = Timer
        While Timer - x < Pause 'This does the pausing
            DoEvents
        Wend
      Next i
     
      If J = Loops Then
      J = 1
      End If
     
      Next J
 
    End Sub

VBA macro to create a copy of a file as CSV format

$
0
0
Hello all,

I really hope to find a solution to a tricky task.

I have to work in a shared excel sheet with a few people editing it.
What I am looking for is a macro, that when updates are ready to go, changes are safed as XLSM and a copy of what's been done as .csv file in the background. I want to stay in the is excel sheet and continue working and do the updates when needed the same way later.
The macro should be available for every user.

Is this possible?:confused:

I need the csv file as we are running a script were xls is not allowed. But csv does not allow to share etc.
Any questions, please ask.

Thanks for your input, stay safe,
2Dizzy

Macro to open file, select tab, and copy 2 ranges.

$
0
0
Hello all,

I'm trying to write a macro that does the following:

In the source workbook User clicks Macro button
Macro begins by prompting the select file window so the user can select which file to copy from

***at this point I would also like the macro to allow the user to select the tab to copy from***

Once the tab is selected, the macro would then copy to ranges from the tab, and paste it into the source workbook.
Macro closes the file from which data was copied, without saving the file.


Where I'm stuck and would appreciate your excel wisdom is the part for selecting the tab to copy from. I got the following code, but I can't figure out how to allow the user to select a specific tab from the file the macro opened.

Code:

Sub pull_data()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*xls*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
        OpenBook.Sheets(1).Range("A1:E20").Copy
        thisWorkbook.Worksheets("SelectFile").Range("A10").PasteSpecial xlPasteValues
        OpenBook.Close False
    End If
End Sub

VBA Macro to Create Workbooks that Include Specific rows and columns from another Tab

$
0
0
Good afternoon,

I would like to know if there is a VBA macro to create new workbooks which will only include specific data from another tab. In the attached "Example.xlsx" I have identified on the summary tab the workbook name and an ID that corresponds to an ID on multiple rows of the Data Tab. I am looking to run a VBA Macro to create Workbooks 1-5 which I have attached. I am having trouble because the rows on the data tab have duplicated IDs.

thanks,

Adamshl

Save As dialog box using a button

$
0
0
Hello!! I hope all is well.

Preface: I have a macro enabled excel file. Within that file, I have a button that the user can click and it will will pull up the Save As dialog box allowing the user to select the location to save the file.

Issue: When the file dialog box is shown, I need the File Name to read: "Client_Name " & Range("AO3").Value which is a cell containing a date (mm-dd-yyyy) and the filetype to be a Macro Enabled workbook or .xlsm file. Currently, I have the file type showing up correct but I cannot get the File Name to update properly.

Code:

Dim fName As String
  fName = "Client_Name " & Range("AO3").Value
  With Application.FileDialog(msoFileDialogSaveAs)
        .AllowMultiSelect = False
        .FilterIndex = 2
       
            If .Show Then
                ActiveWorkbook.SaveAs Filename:=fName, _
                FileFormat:=xlOpenXMLWorkbookMacroEnabled
        'Else
            'MsgBox "The file did not save.", vbCritical
            'Exit Sub
            End If
    End With
End Sub

Even when I remove the fName string and type in the name I want in Filename:= it will not update.

Help please!!! Thank you!!

Alternate code required for extracting data

$
0
0
The following code extracts data from pdf file to text file but only if you have adobe acrobat installed. I need alternate code for this so that if adobe acrobat is not installed, the code should work. Help would highly be appreciated.
Code:

Sub convertpdf2()
'convert pdf to text file
Dim AcroXApp As Acrobat.AcroApp
Dim AcroXAVDoc As Acrobat.AcroAVDoc
Dim AcroXPDDoc As Acrobat.AcroPDDoc
Dim Filename As String
Dim jsObj As Object
Dim NewFileName As String

Filename = "C:\Users\Xahid\Desktop\sample\farmers history gradewise.pdf"
NewFileName = "C:\Users\Xahid\Desktop\sample\test.txt"

Set AcroXApp = CreateObject("AcroExch.App")
'AcroXApp.Show

Set AcroXAVDoc = CreateObject("AcroExch.AVDoc")
AcroXAVDoc.Open Filename, "Acrobat"

Set AcroXPDDoc = AcroXAVDoc.GetPDDoc
Set jsObj = AcroXPDDoc.GetJSObject
jsObj.SaveAs NewFileName, "com.adobe.acrobat.plain-text"

AcroXAVDoc.Close False
AcroXApp.Hide
AcroXApp.Exit

'Call copy data from text file to excel
'ReadFileLineByLine

End Sub

One line of Data duplicated into multiple lines changing values of some lines

$
0
0
Hi all,

Struggling with this one, even how to describe it.

I have a raw data sheet that has lines of data, for this example I have only used 1 "R order number" (Column E) but in reality there could be 50 to 100. Each R Order Number could have several lines in the Raw Data sheet, and the count is based upon "R Line Number" (Column Y). This example has 1,2 and 3.

On each of those three lines will have subtle differences in several columns which would cause the requirement for a copy of a line to be pasted into the extract sheet and edit Column AM with a new value. These rules are extensive and are included in the workbook. So the three rows can become 10 rows in the extract. The next set of data is appended to the bottom. of the extract list.

I am at a complete loss. The VBA I have created is creating duplicate from RAW Data to the extract sheet, but then I start struggling with amendment of column AM.

So for instance

First rule is if Column AM has a value of "BR", then paste two identical rows in the extract sheet, and in one row put "B" in column AM, and in the other row, put "R" in column AM.

So if each of my RAW Data rows 1,2 & 3 have BR in AM, then I will need 6 rows.



Code:

Private Sub ConunandButton1_C1ick()
a = Worksheets("Raw Data").Ce11s(Rows.Count, 1).End(xlUp).Row 'a counts last row in sheet

For i = 2 To a  'from row 2 to a(last row in sheet1)

If Worksheets("Raw Data").Cells(i, 39).Value = "BR" Then  '(if column 39 equals the criteria - amend column number to assess)

    Worksheets("Raw Data").Rows(i).Copy
    Worksheets("Extract").Activate
    b = Worksheets("Extract").Cells(Rows.Count, 1).End(xlüp).Row
    Worksheets("Extract").Cells(b + i, i).Select
    ActiveSheet.Paste
   
    Worksheets("Extract").Cells(b + i, i).Select
    ActiveSheet.Paste
 
   

   
End If

Next

Application.CutCopyMode = False




Sorry all, I am just struggling with this one. The rules have been handed to me so trying to do my best to explain. Any Help is appreciated.
Attached Files

Need help trying to hide rows based on a checkbox in excel

$
0
0
Hi,

I have written some code in order to hide rows based on a checkbox. Initially I wrote the code to hide rows based on a value in a cell and it worked fine, however when i moved to a checkbox it did not work. I have pasted part of the code below.

Code:

Private Sub Worksheet_change(ByVal Target As Range)
ActiveSheet.Activate

If Not Application.Intersect(Range("A18"), Range(Target.Address)) Is Nothing Then
    Select Case Target.Value
    Case Is = "TRUE":  Rows("39:47").EntireRow.Hidden = False
                  ' Rows("39:47").EntireRow.Hidden = True
    End Select
  End If

If Not Application.Intersect(Range("A19"), Range(Target.Address)) Is Nothing Then
  Select Case Target.Value
  Case Is = "TRUE":  Rows("49:57").EntireRow.Hidden = False
                  ' Rows("59:67").EntireRow.Hidden = True
   
  End Select
  End If

Also the hide and unhide of rows never worked properly can someone please help.

Max & min of 2 ranges meeting a condition

$
0
0
2 ranges in my worksheet B2:B10 & I2:I10 are dynamic cells & keeps on getting updated continuously on real time basis as long as the Workbook remains opened.

2 cells A1 & H1 contains formula (based on time) generates 1 or 0
Example: A1=1 for a certain time period which is continuous (Example A1=1 from 18/03/2020 10:30:00 AM to 18/03/2020 11:00:00 AM)
A1 or H1 does not keeps on generating 1 or 0 at irregular intervals i.e. with above example A1=1 from 18/03/2020 10:30:00 AM to 18/03/2020 11:00:00 AM & it will not become 0 in-between the time period.

I need vba for this worksheet to execute the following 2 actions:
1. Column F (F2:F10) should ‘grab’ MAXIMUM value generated in B2:B10 when A1=1 & similarly Column M (M2:M10) should ‘grab’ MAXIMUM value generated in I2:I10 when H1=1.
& also
2. Column G (G2:G10) should ‘grab’ MINIMUM value generated in B2:B10 when A1=1 & similarly Column N (N2:N10) should ‘grab’ MINIMUM value generated in I2:I10 when H1=1.

Code should execute the above actions ‘speedily’. B2:B10 & I2:I10 are updated or refreshed at a high speed.
Any help is greatly appreciated.

Isolating VBA to Single Workbook

$
0
0
I have a Workbook that has VBA in it. When this workbook is open it causes errors in other open workbooks. How do I limit the VBA to only function in the workbook it's written for or get other workbooks to ignore VBA that aren't part of that workbook?

Macro checking if specific cell is empty every 5 rows, if so- set print area.

$
0
0
My dear programmers,

I 've got a worksheet.
1000 empty labels, one beneath other.
The height of one label counts 5 rows.
My macro fills them with data, so every first cell in a label has the date in it.
(A1=time
4 rows of data
A6=time
...
A11=time
...
A16=time
...
A21=time
...
etc.)

My request is a macro that checks every first cell from a label. If it finds first empty it stops checking and set the print area from A1 to last first cell with the time in it- but column E + 4 rows.

Could you make it? I barely understand how to create a function my own but i can read and understand them.
Search and tried plenty of methods, but i can't figure out the right one. Hoping for Your advice.
I really appreciate Your time. Thanks.

Combining Two Workbook Successfully with Macros or Code

$
0
0
Hello all,
Sometimes it's not that the dog can't learn new tricks, it's timing and frustrations. Oh please help! i you can.
I have two workbooks. Workbook 1(the base workbook called 2020 IT Contract & Project Tracking has a very cool little feature - floating comment boxes. If you click into cell B5 the comment will display in both the merged cell at the top of the workbook and also a floating. I LOVE THIS. (Offered as a sample workbook on Contextures site by a talented Debra Dalgleish.

The 2nd workbook has data validation in certain column in which when selected (I li this option) you can either click into a box to select multiple choices or in the other worksheet you can double click a selection to choose. i emphasize again I like the check boxes.


What I am hoping one of you can do, is take those columns with the data validation in them (checkbox cells) and corresponding lists and move them to the base workbook. There are 5 columns and I don't really care about the date column. One other criteria - Can you make it work? I can move the columns over but darned if I can make it work.

Thank ou so very much for looking. Stay safe and no virus' in your hardware or home. Best... Dianne Souder: confused:
Viewing all 50117 articles
Browse latest View live