FAQ Database Discussion Community

## How do I use the Find function with a variable term, for example Run1, Run2, RunX

vba,excel-vba,loops,variables
Cells.Find(What:="Run:1", After:=Cells(1, 1), _ LookIn:=xlValues, LookAt:=xlPart, _ SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) This is the code that I want to use, but I would like to loop it to find Run:1, Run:2, Run:3... Etc..., Is there a way to add a variable in a reference to find "Run:X"?...

## Excel VBA 2013 Print Image

image,excel-vba,printing
I would like to print an image that shows in a frame on a userform. frame1.Picture = LoadPicture(spath & xPicture & ".jpg") spath is the full path to where the picture is stored. This shows the picture just fine. Now I would like to be able to print it. Is...

## VBA - do not grab header in range

excel,vba,excel-vba
I have code that looks for the header "CUTTING TOOL" using a .Find method. It loops through multiple files and multiple worksheets in the opening files. I have run into the problem that when it goes through multiple worksheets in one open file and the column is empty under the...

## Find column with unique values move to the first column and sort worksheets

excel,vba,excel-vba,sorting
I have 2 worksheets with the same headers in different orders. Headers are I.D, Name, Department, Sales, Start date, End Date and a few others. What I am aiming to do is search through the workbooks in which the headers may be in different orders, find the column which has...

## Removing duplicate rows after checking all columns

excel,vba,excel-vba,duplicates
I have written the below macro to remove duplicate rows after checking all columns. I thought it was working correctly, based on the logic, but the output is not correct, and a few of the rows that should be showing up are being deleted. Can anyone help me with that?...

## Date formatting - making dd/m/yyyy into dd/mm/yyyy

excel-vba,date,format
I got a pretty simple question (but yet I've been stuck at it for some time now). Does anyone know how to make the date value from dd/m/yyyy into dd/mm/yyyy in a variable? dim lastdaylastmonth as date lastdaylastmonth = DateSerial(Year(Date), Month(Date), 0) So this code, as of now, would return...

## INDEX MATCH VBA (return a value based on two criteria)

excel,vba,excel-vba,lookup,formulas
I'm doing some work for a client where they receive a weekly report of customers and regions (two columns, A for Customer & B for Region, in a worksheet). * I've omitted the other columns in this spreadsheet for the sake of clarity They need to match the price on...

## copy only one column if criteria is met (Need to adjust my existing code)

excel,vba,excel-vba
The below code works great for copying an entire row, how do I make it so I only copy over the first column. I have tried altering range with no success? Condition is in J, the only column to copy should be 1st one. Dim cell As Range Dim lastRow...

## adding variables into another variable vba

excel,vba,excel-vba
Dim x As Long Dim y As Long Dim CDTotal As Double Dim CSTotal As Double Dim ETotal As Double Dim FTotal As Double Dim HTotal As Double Dim ITotal As Double Dim ITTotal As Double Dim MTotal As Double Dim TTotal As Double Dim UTotal As Double Dim TotalValue...

## Excel 2013 Add a Connector Between Arbitrary Points on Two Different Groups

excel,vba,excel-vba
I'm working in Excel 2013 to (programmatically) add a straight line connector between the lower right hand corner of a rectangle that is part of a grouped shape with the endpoint of a grouped series of line segments. As it stands, I can't even seem to do this manually on...

## Errors 91 and 424 when iterating over ranges in Excel VBA

excel,vba,excel-vba,range
I am an absolute VBA beginner. I have been trying to create a function that separates a large range into smaller ranges. However, when I try and iterate over the large range, I get errors 91 and 424 interchangeably. Here is the relevant bit of code: Dim cell As Range...

## Concatenate N number of columns between 2 specific column name in VBA Excel

excel,vba,excel-vba
I am trying to concatenate the selected range between 2 specific columns. My first column name is "Product-name" (First column is fixed) and second specific column is not fixed. It can be 3rd, 4th, 5th or N. The name of that column is "Price". I want to concatenate all columns...

## Excel VBA (via JavaScript) - Moving a Sheet to a new location

javascript,excel,vba,excel-vba
With the following code, I am attempting to move a Sheet in my Excel workbook from one location to another. However, instead of making the move - Excel creates a new Workbook. How do I move a Sheet from one location to another within the same Workbook? /////////////////////////////////////////////////////////////////////////// // //...

## VBA Application.OnKey Procedure error - Cannot run Macro

excel,vba,excel-vba
I am working on a module which uses an onkey event to detect if backspace or delete is pressed, if it meets the criteria for the event, the corresponding cells will clear contents. I have a procedure to launch the corresponding sub, but I get an error 'the macro cannot...

## Doing a same action to all the subfolders in a folder

excel,excel-vba
Given below code converts all xlsx files inside "C:\Files\Bangalore" to csv files. Sub xlsxTOcsv() Dim sPathInp As String Dim sPathOut As String Dim sFile As String sPathInp = "C:\Files\Bangalore\" sPathOut = "C:\Files\Bangalore" Application.DisplayAlerts = False sFile = Dir(sPathInp & "*.xlsx") Do While Len(sFile) With Workbooks.Open(fileName:=sPathInp & sFile) .SaveAs fileName:=sPathOut &...

## MACRO that organises, groups, outlines (Need to adjust the area that the macro applies to)

excel,vba,excel-vba
How to apply this from A4 instead of A2. Everything else I am happy with. I just want to understand any changes that I need to make to this. Is it needing changes at "set population"? The 2? Sub formatresults() Dim lastRow As Long Dim pop As Range Dim rpSet...

## search compare columns sheet 1 & sheet 2 and change a cell in sheet 1

excel,vba,excel-vba
I really need some help. Problem: I have a workbook with 2 worksheets. Both sheets has headers. Sheet1 is a list of account numbers in column A and the same for sheet 2 column A. Now, what I need to do is this: if I place a date in column...

## Object Variable or With Block Variable Not set in loop using find function

vba,excel-vba,loops,object,find
Sub Main() Dim FName As Variant, R As Long, DirLoc As String, i As Integer R = 1 i = 1 DirLoc = ThisWorkbook.Path & "\" 'location of files FName = Dir(DirLoc & "*.csv") Do While FName <> "" ImportCsvFile DirLoc & FName, ActiveSheet.Cells(R, 1) R = ActiveSheet.UsedRange.Rows.Count + 1...

## VBA code to sum totals grouped by invoice

excel,excel-vba
I am new to vba and would like to automate a rather manual process in excel 2007. I have a list of invoice numbers in column A (can be up to about 500 lines long), a list of items and any associated accessories in column B and the invoice value/amounts...

## Msgbox With If statement

vba,excel-vba,excel-2003
I'm trying to get a box to pop up listing a number of values that could be blank. MsgBox (res1 & vbNewLine & _ res2 & vbNewLine & _ res3 & vbNewLine & _ res4 & vbNewLine & _ res5 & vbNewLine & _ res6 & vbNewLine & _ res7...

vba,excel-vba
Having a little trouble with my userform, its not unloading once i hit the command button the data is inputted to the sheet but the userform is not refreshed and the data stays in the text boxes. It was working fine until i put the data validation in, but i...

## VBA how to initialize vCPath

vba,excel-vba,excel-2010
How do I initialize vCPath? VBA Run-Time Error 1004 @Garry's Student says I "must somehow use the info you get from Application.FileDialog(msoFileDialogOpen) to generate the full filespec of the file you wish to open". What's the simplest way to do this? I am a VBA beginner: I have been programming...

## Slow VBA macro writing in cells

excel,vba,excel-vba,ms-project
I have a VBA macro, that writes in data into a cleared out worksheet, but it's really slow! I'm instantiating Excel from a Project Professional. Set xlApp = New Excel.Application xlApp.ScreenUpdating = False Dim NewBook As Excel.WorkBook Dim ws As Excel.Worksheet Set NewBook = xlApp.Workbooks.Add() With NewBook .Title = "SomeData"...

## Using a stored integer as a cell reference

excel,excel-vba,reference
Dim x As Integer Dim y As Integer For y = 3 To 3 For x = 600 To 1 Step -1 If Cells(x, y).Value = "CD COUNT" Then Cells(x, y).EntireRow.Select Selection.EntireRow.Hidden = True End if If Cells(x, y).Value = "CD Sector Average" Then Cells(x, y).EntireRow.Select Selection.Insert Shift:=xlDown Cells(x +...

## Compare 2 sheets with different headers

excel,vba,excel-vba,compare
I have 2 different files which have different headers, for example: OldfileHeaders | NewFileheaders ID | Test ID Date | New date and so on. I am trying to compare the data in both sheets and see if they match. The rows of data may be in different order and...

## VBA Compile error What is the cause and solution?

excel-vba
Set myIE = New InternetExplorer myIE.Silent = True myIE.navigate sURL myIE.Visible = False Do While myIE.Busy Do Until myIE.ReadyState = READYSTATE_COMPLETE Loop Loop Application.Wait (Now() + TimeValue("00:00:02")) Set HTMLDoc = myIE.document HTMLDoc.getElementById("loginID").Value = ICUSER HTMLDoc.getElementById("password").Value = ICPASS For Each oHTML_Element In HTMLDoc.getElementsByTagName("input") If oHTML_Element.Type = "submit" Then oHTML_Element.Click: Exit...

## EXCEL VBA: How to manupulate next cell's (same row) value if cell.value=“WORD” in a range

excel,vba,excel-vba
I want to change the next cell in same row in a if cell.value="word" in a range. I have defined the range, using 'for' loop. In my code, if cell.value="FOUND THE CELL" then cell.value+1="changed the next right side cell" cell.value+2="changed the second right side cell" end if I know this...

## Copying certain columns VBA

excel,vba,excel-vba
I have a working VBA macro which copies from one spreadsheet 'AverageEarnings' to another 'Sheet1', under the condition that Column AO has the word 'UNGRADED' in it. The macro copies the entirety of these conditional rows to Sheet1. I am looking to copy columns B and C ('AverageEarnings') to columns...

## (VBA Excel) Extract Text and related Letter from String and output result

regex,string,excel-vba,character,number-formatting
So the scenario I have is there are letter with a number: Desired Output after Program (Note an underscore is visually used but I need a space: ____________F __G _____E __G__E______F Currently I have written code in the Number and First Letter Column to extract the number and first letter:...

## Simple Enquiry with Complex Answer - How do I Select RowA6-Row(last non-blank) for a simple formula

excel,excel-vba,cell,calculated-columns,calculated-field
I have many columns all labeled with many many values underneath, which can be words or numbers Here is the current equation =INDEX(AK6:AK94,MODE(MATCH(AK6:AK94,AK6:AK94,0))) I have this on the in cell 5 of each column. The number of values in each column may increase or decrease. If i reference the entire...

## Sort multiple columns of Excel in VBA given the top-left and lowest-right cell

excel,vba,excel-vba,sorting
I am trying to sort these three columns (Sort By Col-2) in excel using VBA. Top-left (Row number and Column number e.g. 1,1) and lowest-right cell (Row number and Column number e.g. 9,3) are known. Every cell contains the values of String type. Input: Col-1 Col-2 Col-3 P1 I1 XYZ...

## using activecell and offset in VBA

excel,vba,excel-vba
I am trying to test offset property in excel vba . I am using a simple code which selects the cell which is daigonal , i.e 1 row and 1 column away from the active cell. This is what I am doing Sub Range_Offset() Range(ActiveCell).Offset(1, 1).Select End Sub I have...

## Excel vba code using ThisWorkbook.Sheets(1).Range not working, but Sheet1.Range works fine. Why?

excel,vba,excel-vba,object
When I use wb.Sheets(1).Range("A:A").Find(What:=ID, LookIn:=xlValues) I get error 91 - Object Variable or With Block not set. When I use Sheet1.Range("A:A").Find(What:=ID, LookIn:=xlValues) it returns correct value. Why the difference? Is there a flowchart I can reference or any simple information available to understand which sub-commands (I don't know the proper...

## Excel VBA User-Defined Function: Get Cell in Sheet Function was Called In

excel,vba,excel-vba,user-defined-functions
I have a user-defined function in Excel that I run in multiple sheets. I am trying to use Cells(i, j) to pull the value of cells by their row and column in the sheet in which my function is called. Instead, Cells(i, j) pulls the value of cell [i,j] in...

## Using a cell's number to insert that many rows (with that row's data)

excel,excel-vba
I have data in excel that looks like this {name} {price} {quantity} joe // 4.99 // 1 lisa // 2.99 // 3 jose // 6.99 // 1 Would it be hard to make a macro that will take the quantity value ("lisa // 3.99 // 3") and add that many...

## Excel-VBA: create named Range in row until end of cell content

vba,excel-vba,range
Imagine an Excel sheet with some rows and some content in each row (i.e. different column-length for each row). In Excel-VBA: How can I create a range-X within column-X that goes from row-cell-2 to the end of the content of this X-column ?? i.e. I would like to create a...

## VBA - Trapping events on dynamically created Textbox

excel,vba,excel-vba,events,userform
I am writing a VBA application in Excel. I have a Userform that dynamically builds itself based upon the data contained in one of the worksheets. All of the code that creates the various comboboxes, textboxes and labels is working. I created a class module to trap OnChange events for...

## VBA to remove special characters before saving workbook

vba,excel-vba,special-characters
I found this function to remove special characters. Function Remove_Characters(s As String) As String Static RegEx As Object If RegEx Is Nothing Then Set RegEx = CreateObject("VBScript.RegExp") With RegEx .Global = True .Pattern = "\\|/|:|\*|""|\?|<|>\|| " End With End If Remove_Characters = RegEx.Replace(s, "") End Function What I want to...

## VBA macro - specifying columns with copy paste.

excel,vba,excel-vba
I have a partially working VBA macro which copies from one sheet 'AverageEarnings' to one of two ('SicknessRecordGraded', 'SicknessRecordUngraded') on condition that a string is found in column 41 ("GRADED", "UNGRADED"). I want the macro to copy values from columns B,C ('AverageEarnings') to columns A, B on the other sheets,...

## ReplaceLine method in VBE only replacing part of line

excel-vba,vbe
In response to this question I thought it would be fun to write a VBE macro that would automatically replace lines which look like DimAll a, b, c, d As Integer by Dim a As Integer, b As Integer, c As Integer, d As Integer In my first draft I...

## VBA dictionary data type

excel-vba,dictionary,key
Many sources, e.g. https://support.microsoft.com/en-us/kb/187234, claim the key of a dictionary can be of many data types beyond string. However, when I tried integers and dates as keys, it fails. Can someone explain? I tried the answer of @Tim Williams below, it works. What I had before was Private Sub trial()...

## VBA - .find printing wrong value

excel,vba,excel-vba
I have two sections of code that basically do the same thing but with two different columns. The code finds the header "CUTTING TOOL" and "HOLDER" (looping through multiple files) and prints the information from those columns into one worksheet, masterfile. I was using a less efficient method of setting...

## Extract text which begin with the same two characters and end in a numeric character

regex,vba,excel-vba,user-defined-functions,udf
I would like to extract a code from a larger extract of text, the constants I have is the Code will either start with WP or MD and end in a Numeric value and example of the patterns the code can be in are below; WP0053 WP053 WP_053 WP_0053 WP...

## Interface Controls for DoEvent in Excel

excel,vba,excel-vba,loops,doevents
I have a macro to loop through a range and return emails to .Display based on the DoEvents element within my module. I iterate that: row_number = 1 'And Do DoEvents row_number = row_number +1 'Then a bunch of formatting requirements Loop Until row_number = 'some value I am wondering...

## Regular Expression for HTML

regex,excel-vba
From this string: <strong class="big zindex-pt zindex-pt-all">&pound;2,362,214</strong> I am trying to get &pound;2,362,214 using this RegEx in Excel VBA: .Pattern = "<strong class="big zindex-pt zindex-pt-all">([\s\S]*?)<" Any ideas what I am doing wrong?...

## Retrieve Number from a website into Excel

excel,excel-vba
From this website http://bit.ly/1Ib8IhP I am trying to get this number into an Excel cell. Avg. asking price in Bayswater Road: £1,828,502 Is there any way using VBA or another tool? Couldn't make it work with a web query....

## Match Function in Specific Column Excel VBA

excel,vba,excel-vba,match,worksheet-function
I'm trying to write a program in VBA for Excel 2011 that can search a column (which column that is is determined by another variable) for the number 1 so that it knows where to start an iteration. Say that the number of the column is given by colnumvar. The...

## Excel VBA - Add row & make active

excel,excel-vba
Good evening Please see the attached image for an example of my data. The strings in column A are grouped together. The below code is a WIP to achieve the following... Find the last occurrence of each delivery location & add a new row after. In the newly created row,...

## read variable excel data into variant with the same format

excel,vba,excel-vba,variables,data-structures

## VBA Excel SendKeys Macro

excel,vba,excel-vba
I have some result data in sheet Extract that I need to activate cell by cell and press enter. It's alright for 10 cells but I have over 40 000. So i wrote some macro Sub Refresh() Dim lastrow As Long lastrow = ActiveWorkbook.Worksheets("Extract").Range("Q" & rows.Count).End(xlUp).Row For j = 2...

## If cell value starts with a specific set of numbers, replace data

excel,vba,excel-vba
My cell values are strings of numbers (always greater than 5 numbers in a cell, ie 67391853214, etc.) If a cell starts with three specific numbers (ie 673 in a cell value 67391853214) I want the data in the cell to be replaced with a different value (if 673 are...

## Range.offset propety

excel-vba
I'm trying to understand a code on VBA, to debug the VBA program of someone. So I want to know that is the property and the meaning of Range (Value).offset(x;y). Here is my code: `Sub initialise() Dim i As Double, j As Double For i = 0 To maxnodes -...

## Excel - How to show the last date different worksheets were changed

excel,excel-vba
This is my scenario: I have an excel Workbook with a number of different Worksheets. This Workbook is given to project managers within my organisation to complete. I have a Worksheet within this Workbook titled "Main Menu" which contains buttons that navigate the user to a number of different Worksheets...

## VBA for duplicate rows

excel-vba,duplicates
I have a sheet of columns. I want to compare data in multiple columns, and return a flag in another column to indicate rows that are duplicates. I found a little code online which was meant for checking one column of data, and have so far been unsuccessful in being...

excel,osx,vba,excel-vba,excel-vba-mac
This snippet of code appears to run perfectly fine in Excel on Windows. But on OSX, its erroring out with a "Named argument not found (Error 448)". With Sheets("Colors") Set rangeFound = .Cells.find(What:=Resource, After:=.Cells(1, 1), LookIn:=xlValues, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) End With ...

## Delete the Range of Columns in Excel VBA

excel,vba,excel-vba
I am trying to delete the range of columns but getting error "Application Defined or object defined error". In the below code wks is the worksheet and colStart and colEnd are variables with values. Dim colDelete As String colDelete = wks.Range(wks.Cells(1, colStart), wks.Cells(1, colEnd)).EntireColumn.Delete ...

## Paste pivot table as bitmap into Body of Outlook Appointment

excel-vba,bitmap,outlook,paste,appointment
Using Excel VBA, I'd like to make a small pivot table visible to Outlook users. I do NOT want to paste into a message body I DO want to paste into an appointmentItem Here is my code that creates the Appointment and copies Range to clipboard. How do I paste...

## Excel VBA - ShowAllData fail - Need to know if there is a filter

excel,vba,excel-vba,filter
I have automated a proper record input into the table that I use as a database, and when the table is filtered the input don't work. So I have code this to unfilter DataBase before every record input. Public Sub UnFilter_DB() Dim ActiveS As String, CurrScreenUpdate As Boolean CurrScreenUpdate =...

## Vba changing directory to save

excel-vba
I'd like to save a file in a directory whose name changes according to the name of the Previous Month. Here is the code: name_month = MonthName(Month(Date) - 1) Set Newbook = Workbooks.Add With Newbook .Title = "TESO1" .SaveAs Filename:="C:\Users\ee31264\Desktop\Mensile Automat\name_month \send\TESO1.xlsx" End With Newbook.Close unfortunately the name_month i wrote...