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

Concatenate multiple cells in column

$
0
0
I need to be able to combine the cells per line in one cell ignoring all the blacks. Values are separated with a comma.
Attached Files

[SOLVED] Changing file destination and filename based on specified in cell in VBA code

$
0
0
Hi everyone,

As new to VBA, how can I modify this so instead of objChart.Export ("C:\Users\dean.martin\Desktop\My Exported Charts\Yesterday's Weather.jpg"), it would use the folder location specified in cell "N10" of "sheet 1" for example? (ie., where N10 = C:\Users\dean.martin\test\ or any other destination folder) and in cell "N9" of "sheet 1" for the file name (ie., where N9 = Today's weather.jpg or any other file name or format)

Below is my code;

---------------------------------------------------------------------------
Private Sub CommandButton1_Click()
Dim i As Integer
Dim intCount As Integer
Dim objPic As Shape
Dim objChart As Chart
'copy the range as an image
Call Sheet1.Range("A1:J57").CopyPicture(xlScreen, xlPicture)

'remove all previous shapes in sheet2
intCount = Sheet2.Shapes.Count
For i = 1 To intCount
Sheet2.Shapes.Item(1).Delete
Next i
'create an empty chart in sheet2
Sheet2.Shapes.AddChart
'activate sheet2
Sheet2.Activate
'select the shape in sheet2
Sheet2.Shapes.Item(1).Select
Set objChart = ActiveChart
'paste the range into the chart

Sheet2.Shapes.Item(1).Line.Visible = msoFalse
Sheet2.Shapes.Item(1).Width = Range("A1:J57").Width
Sheet2.Shapes.Item(1).Height = Range("A1:J57").Height
objChart.Paste
'save the chart as a JPEG
objChart.Export ("C:\Users\dean.martin\Desktop\My Exported Charts\Yesterday's Weather.jpg")
End Sub
-----------------------------------------------------------------------
Any help would be greatly appreciated.

Thanks,
Dean

Smart way to create a standard Word Report with Excel data (Bookmarks?)

$
0
0
I have for quite some time now been looking into finding a way to create a standard Word Report that i will be using over and over, with data from various excel sheets. The layout of the report is predefined, however at different locations in the report
i need figures/tabels/data/text to be changeable, based on what project i am working on.
Initially i thought the "Paste Special, As link" feature could be the solution but after trying to make it work for quite some time, i've given up on that, as it keeps messing up my documents and breaking links for no apparent reason.

So then someone suggested i tried using Bookmarks to define where i want to input text/figures to Excel.

To some degree this is working in the sense that i have created a VBA modul that enables me to copy data from Excel to a specific point in the Word report (Predefined Bookmark) - However after the data is copied, i can't figure out a way to enable me to change the text that i now have in my word document, in case there is changes in the excel document. Essentially its a one-time transfer solution.

Essentially i want to end up with something where i have a Word Document with a Macro button in it i can press, which will check for all the bookmarks i have defined, and update their values, based on the current values of the excel sheets that they are retrieved from.
Can i do that with Bookmarks?

Or should i try and go in a different direction?

Thanks,
Nicolai

Understanding a script, why are all the text in cells in column AA1 to AT114 deleted?

$
0
0
I have this script to merge 17 different excel sheets into one. Im also wanting to make something happen i columns AA and AB but what I
noticed was that after merging it seems to delete all text in cell AA1 to AT114. When running through the script it seems to occur at the point of
merging the excel files together. Does anyone know why this happends?

see script;

Code:

Dim bookList As Workbook
            Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
            Application.ScreenUpdating = False
            Set mergeObj = CreateObject("Scripting.FileSystemObject")
 
            'Change folder path of excel files here
            Set dirObj = mergeObj.Getfolder("G:\Arbeid\MSS_ModelBuilder_Temp_Files\ArcGIS\scratch")
            Set filesObj = dirObj.Files
            For Each everyObj In filesObj
            Set bookList = Workbooks.Open(everyObj)
 
            'Change "A2" with cell reference of start point for every files here
            'for example "B3:IV" to merge all files start from columns B and rows 3
            'If you're files using more than IV column, change it to the latest column
            'Also change "A" column on "A65536" to the same column as start point
            Range("A1:IV" & Range("A65536").End(xlUp).Row).Copy
            ThisWorkbook.Worksheets(1).Activate
 
            'Do not change the following column. It's not the same column as above
            Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
            Application.CutCopyMode = False
            bookList.Close

            Next

Create Folder and sub folder at desktop

$
0
0
dear all
PFA..in sheet i want to create folders which is under "File Number" than in it sub folder which under "Cont_Name" all save at desktop in one folder


Regards

Gondal
Attached Files

handling of #N/A in a cell

$
0
0
Hi,

I am populating a sheet from an external source. Sometimes the query doesn't result data.
When I work with those cells, I am facing, that I cannot manage the #N/A as value, even with ISERROR function.
If my loop finds an #N/A , it stops with type mismatch and throws Error 2042.

I do it like this:

Code:



If mycell.Offset(i, 1) = "myvalue" Or IsError(mycell.Offset(i, 1)) then
  mycell.Offset(i, 1) = "newValue"
end if

Thank you for help

Efficiently printing multiple pages (determined by checboxes.userform) as one print job

$
0
0
I used very inefficient code to manually printout each sheet name when each box is checked. The problem is that each sheet becomes its own print job. I am hoping it would be possible to use vba code to select all of the relevant tabs (at the same time) and then print all of them at once.

I came across lots of lengthy code around the web that is honestly over my head. I came across the following code (to at least select the tabs for me) posted to one of these forums years ago. In concept it is exactly what I want, but I'm not sure why it's not working.

My userform checkboxes are each named PrintBox1, PrintBox2, etc. and my tabs are named Sheet1, Sheet2. The tab names (in properties) and check box names are related to each other (i.e. PrintBox1 should print Sheet1, etc.).

Any help is hugely appreciated, thank you in advance!


Code:

Private Sub Print_Click()
Dim i As Long, txt As String
For i = 1 To ThisWorkbook.Sheets.Count
    If Me.Controls("PrintBox" & i).Value = True Then txt = txt & vbLf & Sheet(i).Name
Next
If Len(txt) Then Sheets(Split(Mid(txt, 2))).Select
End Sub

*** Copy sub section total value to main section***

$
0
0
Hi All,


I have a data in which there are number of section and sub section values are given.

Requirement is values of sub section need to be added with (main) Section to arrive grand total.

Example in the attached data Column B is Section A and Column C is Sub section A. Total value of subsection A (C14) to be copied to Section A (B15) and then Grand total to be calculated.

Points to be considered

• Need to find out sub section column is available or not against section
• If available total of sub section to be copied to section column (in row 15)
• Grand total to be calculated.
• If no subsection, Sub value (row 15) will became “0”

Plz help with VBA code, in case of any query revert back.
Attached Files

To bold characteres between two words

$
0
0
Hi all,

I am looking to format (i.e., bold) few words between two characters across the entire worksheet using vba.

I want to define the start word and end word and bold all the words between these two words.

Ex. in the given sheet I want to bold "April - 2016" then I define start word "the" and end word "along" and bold the word.

Help please.
Attached Files

Highlighting items in listbox which prompts message box

$
0
0
Hi, I have the following code which just displays the current open files in the list box. The user then selects the desired file that is open and then that file activates.

What I am wanting to have is when the user selects the file a message box pops up asking the user if they sure that the correct file was selected, if yes then activates but if the user says no then it returns back to the list box.

I have been playing around to try and get it to work but nothing.

many thanks in advance.

Code:

Private Sub ListBox1_Click()
    Windows(ListBox1.Value).Activate
    Unload Me
End Sub

Private Sub UserForm_Activate()
    Dim wkb As Workbook

    For Each wkb In Workbooks
        If Windows(wkb.Name).Visible Then _
          ListBox1.AddItem wkb.Name
    Next
End Sub

Copy a cell and paste it to another cell

$
0
0
Hi all,

I have a table of data which contains numbers showing to 4 decimal numbers and would like to copya certain number to another cell by a condition for example if the reference cell is less than 250 then copy this cell and if the reference cell is greater than 250 and less tham 500 copy that cell and so on.... I have used the following code. The code is fine but the problem is when the number is copied to the destination cell it will round up and down the number after the second decimal point which make my calculations wrong. i.e if the number meant to be 0.0821 it will be displayed as 0.0800 or if the number supposed to be 0.0781 it also displays as 0.0800. Any idea how can I fix this? Any help appreciated.

Thanks.

Code:

        If Sheets("Calculations").Range("H13").Value = 0 Then
        Sheets("Financial").Range("C13").Value = ""
        End If
       
        If Sheets("Calculations").Range("H13").Value > 0 And _
        Sheets("calculations").Range("H13").Value < 250 Then
        Sheets("Financial").Range("C13").Value = Sheets("Financial").Range("C18").Value
        End If
       
        If Sheets("Calculations").Range("H13").Value >= 250 And _
        Sheets("Calculations").Range("H13").Value < 500 Then
        Sheets("Financial").Range("C13").Value = Sheets("Financial").Range("C19").Value
        End If
       
        If Sheets("Calculations").Range("H13").Value >= 500 And _
        Sheets("Calculations").Range("H13").Value < 5000 Then
        Sheets("Financial").Range("C13").Value = Sheets("Financial").Range("C20").Value
        End If
       
        If Sheets("Calculations").Range("H13").Value > 5000 Then
        Sheets("Financial").Range("C13").Value = Sheets("Financial").Range("C21").Value
        End If

[SOLVED] Data of array

$
0
0
Hi everybody!

I'm a beginner in VBA and need your help please!!
I have a problem with a code I wrote to apply an operation on an array. I need to take the values of the sheet "TRI" from the row 2 and column 3 to the end. Divide them by the values of cells (i, 2). Then past values in the sheet ("typology"). I'm searching the problem from long time but I can't see what is wrong! It bugs on the red line:

This is the code :
Code:

Dim tab1(), tab2()
Dim i As Integer, j As Integer
Dim WsD As Worksheet, WsT As Worksheet
Set WsD = Worksheets("TRI")
Set WsT = Worksheets("TYPOLOGY")

With WsD
i = .Cells(1, 1).End(xlDown).Row
j = .Cells(1, 1).End(xlToRight).Column
     
            tab1 = .Range(.Cells(1, 1), .Cells(i, j)).Value
            End With
With WsT
            tab2 = .Range(.Cells(1, 1), .Cells(i, j)).Value
            End With
           
With WsT

  i = .Cells(1, 1).End(xlToRight).Row
  j = .Range("A1").End(xlDown).Column
 
        For i = 2 To UBound(tab2, 1)
            For j = 3 To UBound(tab2, 2)
            tab2(i, j) = tab1(i, j) / tab1(i, 2)
            Next j
        Next i
       
  .Range(.Cells(1, 1), .Cells(i, j)).Value = tab2
  End With

End Sub

Thank you very much if you can explain me what is wrong!

Output Data to Form and Ask User to Confirm

$
0
0
Hi guys, I have a macro that runs and pulls data from a user-selected workbook and formats it in a certain way. Before it takes the data and adds it to the active workbook, I want to run it by the user in a form and allow the user to accept, reject, or accept & flag each data item. I have essentially no experience with userforms and was hoping someone could point me in the right direction. What userform objects should I start with? Thanks

Attached is a mock-up of what the form will look like.

help with VBA VLOOKUP

$
0
0
Hi,

I´m trying to get a description when I insert the product code, i´m using VLOOKUP, however i can´t retrieve text on "Textbox2"....only numbers are show....

Can you help me??

Quote:

Private Sub textbox1_AfterUpdate()


Dim FoundValue1 As String
Dim LookupValue As String


LookupValue = TextBox1.Text

On Error GoTo ErrorHandler:

With Application.WorksheetFunction

FoundValue1 = Round(.VLookup(CDbl(LookupValue), Sheets("Folha1").Range("A:B"), 2, False), 2)




End With
TextBox2.Text = FoundValue1


GoTo NoError:

ErrorHandler:
TextBox2.Text = "Not Found"

NoError:

End Sub




Here is a exemple to download and test....

https://www.hidrive.strato.com/lnk/xdGAUlxb

Hide / Unhide rows based on contents of cells VBA

$
0
0
I would like to hide rows in Sheet 1 depending on text in cells A15-A18.

A number is picked from a dropdown box in cell D13. This triggers certain role descriptions to appear on cells A15:A18.

Rows 22-24 will be hidden and I want them to only be unhidden if the corresponding role description appears in cells A15:A18

e.g. If Team leader appears in in cells A15:A18 I would like row 22 to be unhidden

I have attached a test spreadsheet to try and explain my problem better.
Attached Files

Update a different workbook based on ID in entered in userform

$
0
0
Hi there!

I have a userform that contains the following fields: ID, Name, Execution Date, and Expiration Date. With a click of the submit button it will push those information into the designated cells in the excel sheet that will serve as a form.

Similarly, I have another workbook that will serve as a database that will contain the ID, execution date, expiration date and many other detailed information not in the current userform. Is there a way that with the click of submit button or even with a different command button that it will open the other workbook and based on the ID that is entered on the textbox, it will look it up and put in the dates on the designated cell. (please note that the ID, Execution Date and Expiration date will be on the same row within the sheet so they will be next to each other).

My goal is that this workbook will update IF the ID already exist. if not, I would like for a message to appear saying ID not found (or something similar). Can anyone help?

Thank you!

http://i68.tinypic.com/2z8zz28.png

http://i64.tinypic.com/24yu4ut.png
Attached Images

Macro - prompt for file

$
0
0
Hiya!

I have the below code that imports many lines of text from an external .txt file into a single column A, starting at row 3. This was simply generated from the macro recorder.

How do I make this generic and rather pop up and ask for a specific file?

It is always a .txt file, but the file name and location can change.

Also it would be nice if I could name the dialogue box; to say something like "Please choose the log .txt file".


Code:

Sub Import()
'
' Import Macro
'

'
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\K-FrameLog\K-FrameLog.txt", Destination:=Range("$A$3"))
        '.CommandType = 0
        .Name = "K-FrameLog"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlOverwriteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = False
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 65001
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(2)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

As a side note, it failed at .CommandType = 0 and I have no idea why or what this does - but I came across a suggestion to remove it and this seemed to fix it.

Copy picture from Excel to Power point presentation

$
0
0
Hi all,

I would like some help here before I go mental!

I have a number of separate files each with a dashboard/scorecard. The said scorecard has a transparent - ish picture (a specific report template picture) with a number of KPI's that are being updated off a pivot table. I would like to export the whole picture as JPG (or whichever format is suitable) with the updated numbers in it, in a Power Point Presentation.

The problem I have is that I cant seem to find the best way to do it. Looks like the darn thing selects the whole range...

Any help would be greatly appreciated!


Code:

Sub New_PPT_Pic()
   
   
   
   
    'Copy range from main sheet as pic
   
    Range("A1:T1").Select
    ActiveSheet.Cells.Select
    Selection.CopyPicture
   
    'Paste as pic in new sheet called ppt and resize pic
   
    Worksheets.Add.Name = "pptpic"
    Range("A1:T1").Select
    ActiveSheet.PasteSpecial Picture
    Selection.ShapeRange.LockAspectRatio = msoFalse
    Selection.ShapeRange.Width = 550
    Selection.ShapeRange.Height = 315
    Selection.ShapeRange.Left = 0
    Selection.ShapeRange.Top = 0
   
       
    'Copy the picture
    Selection.Copy
   
    '==================================================================================================================
   
   
    'Open new Powerpoint
   
    Dim NewPPT As PowerPoint.Application
    Set NewPPT = CreateObject("PowerPoint.Application")
    NewPPT.Visible = msoTrue
    'NewPPT.Presentations.Open ("C:\Users\pacleanum\Desktop\Mircea\Scorecard dash\Pres TEST")
 
   
    'Add presentation if not there
   
    Dim NewPresenation As PowerPoint.Presentation
    If NewPPT.Presentations.Count = 0 Then
        Set NewPresentation = NewPPT.Presentations.Add
    Else
      Set NewPresentation = NewPPT.ActivePresentation
    End If
   
    'Add title slide if not there
   
    Dim NewSlide As PowerPoint.Slide
    If NewPresentation.Slides.Count = 0 Then
        Set NewSlide = NewPresentation.Slides.Add(1, ppLayoutTitle).Select
        Set NewSlide = NewPresentation.Slides.Add(2, ppLayoutTitleOnly).Select
    Else
        ActivePresentation.Slides.Range.Select
    End If
   
    'Paste pic
    NewPPT.ActivePresentation.Slides(2).Select
    NewPPT.ActiveWindow.View.Paste
   
   
    '==================================================================================================================
   
   
    'Save Powerpoint
   
    Dim ppapp As Object
    Set ppapp = GetObject(, "Powerpoint.Application")
    ppapp.FileDialog(msoFileDialogSaveAs).Show
   
    'Delete PPT sheet
   
  ' On Error Resume Next
  ' Application.DisplayAlerts = False
  ' Sheets("pptpic").Delete
  ' Application.DisplayAlerts = True
   
    'Close Excel
    ActiveWorkbook.Save
   
End Sub

Why is there message that large amount of information on clipboard?

$
0
0
Hi
I am trying to write a VBA for copying worksheet from a workbook selected by user to current workbook. Name of current workbook is Test Template, copying to worksheet named 'SCHEDULE'. After copying, user will be directed to another worksheet named "MAIN". Why is there a message that large amount of information is on clipboard, asking user to save or delete the information?

My VBA looks like this:

Code:

Dim fNameAndPath As Variant, wb As Workbook
fNameAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.XLS), *.XLS", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Set wb = Workbooks.Open(fNameAndPath)
  Cells.Select
  Selection.Copy
  Windows("TEST Template.xlsm").Activate
  Sheets("SCHEDULE").Select
  Cells.Select
  ActiveSheet.Paste
  Sheets("Main").Activate

wb.Close savechanges:=True 'or false
End Sub

Pl help. Thanks.

Format table with variable number of entries

$
0
0
also in http://www.mrexcel.com/forum/excel-q...ml#post4522474


Hi everyone,

I'm trying to get a file formatted automatically. This file is extracted from another program every week or so.
In the image (couldn't upload a xlm file for some reason), you can see an example of what I want to achieve. At the top, you see how the data is initially formated, and below how I want it to be.
I've created a macro but the problem is that the macro only works for files with the same number of entries. This table as a variable number of entries: 1 week it has 10 rows, the other 15, the next 8...you get the idea :)
How can I format the file for a variable number of entries?
vba.png

Thank you,
ccarvalho
Viewing all 50262 articles
Browse latest View live