How to paste values in a certain text position in VBA? - vba

I have a workbook with 2 sheets. First sheet contains table with data to copy, the second sheet contains strings inside which i would like to insert copped data.
The problem is that i don't know how exactly to define 2nd sheet strings a text start/end position, where i would like to paste?
For example:
on a first sheet i have in range A1:A4
<Tracciato xmlns="http://">
<Riquest>
<Test>
<Code></Code>
Then i take from a second sheet B2 cell a value 293 and insert it between , so i get:
<Tracciato xmlns="http://">
<Riquest>
<Test>
<Code>293</Code>
The code could be something like:
Sub Data()
Sheets("First_sheet").Select
Sheets.("First_sheet").Range("B2").Copy Destination:=Sheets("Second_sheet")
End Sub

Here is a brief example:
Sub foo()
Dim copyRange as Range
Dim destRange as Range
Dim copyString as String
'Define the cell from which you want to "copy" the text
Set copyRange = Sheets("First_Sheet").Range("B2")
'Define the destination:
Set destRange = Sheets("Second_Sheet").Range("B2")
'Assign the value from a cell to this string variable
copyString = copyRange.Value
'Now insert the text:
destRange.Value = Left(destRange, 6) & copyString & Right(destRange, 7)
End Sub
Of course, practically speaking you will most likely need to implement this in some sort of Loop structure. YOu may need to use some logic to determine where the destination is, if that is not a 1:1 relationship (i.e., B2 on Sheet1 --> B2 on Sheet2, etc.). You may also need to use some logic to better define the start/end for where to insert. Right now the example code ONLY is for inserting values to a node like <Code></Code>.

Related

vba excel macro button, change only a specific cell, replacing with different data in other sheet

How do I get a button to change one cell value each time the button is pressed,
lets say cell B5 is the active cell and I want this value to changed every time I click the button based on the values in a different sheet A1:A10,just going down the list.
Sub Button2_Click()
Sheets("data").Range("A1:A10").Copy
Sheets("printing").Range("B5").PasteSpecial xlPasteValues
End Sub
I want to create a sort of loop, example I'm printing the same file many times but changing the names(in a cell), I have a list of names in a sheet called data, every time I click the button I want the (different sheet called printing) cell B5 to change.
I can simply do this with copy and paste however its about 250 names I was hoping for a simpler solution.
It think that this is about what you are looking for.
The subroutine below sets the value of cell B5 on sheet 2 to be the value of the cell that corresponds to the index, iterating over down columns then rows (A1, A2, ... A20, B1, B2, B20 in the example below)
You can learn more about the static statement, which makes this work here.
Sub iterateStatic(Optional Reset As Boolean = False)
Static index As Integer
Dim fromRng As Range, _
targetRng As Range
If Reset Then index = 0
Let index = index + 1
Set fromRng = Sheets(1).Range("A1:B20")
Set targetRng = Sheets(2).Range("B5")
Let targetRng.Value = fromRng.Cells.Item( _
RowIndex:=index Mod fromRng.Rows.Count, _
ColumnIndex:=-Int(-index / fromRng.Rows.Count)).Value
' '' Debug to show how the function iterates over the range
'
' Debug.Print fromRng.Cells.Item( _
' RowIndex:=index Mod fromRng.Rows.Count, _
' ColumnIndex:=-Int(-index / fromRng.Rows.Count)).Address
End Sub

Macro for identical IF statement across multiple worksheets

I've got an simple if statement that I want to use to concatenate the results from multiple (25+) worksheets into one cell on a master worksheet.
If statement is
=IF('400'!C23="y",'400'!$C$2,"")
My current method is to bash multiple IF statements together into a really long string (see below) but I'd rather make a function (say, ifconcat() )that I can call up that uses a table list of my tab names to go through each worksheet. Can anyone help me with this?
IF('400'!C23="y",", "&'400'!$C$2,"")&IF('410'!C23="y",", "&'410'!$C$2,"")&IF('420'!C23="y",", "&'420'!$C$2,"")
will currently return values in C2 from sheets 400, 410 and 420.
Thanks for any help!
Try the following UDF. It fetches and concatenates values from many worksheets where matchVal parameter is matched. matchCel is the cell to compare and getCel is the cell to concatenate if the match succeeds. The parameter sheetNames is an optional list of worksheets to lookup; If this parameter is missing, the values are fetched from all worksheets except the caller worksheet.
Function FetchSheets(matchVal, matchCel As Range, getCel As Range, ParamArray sheetNames()) As String
Dim sheetCol As New Collection, sh
If UBound(sheetNames) < 0 Then
For Each sh In ThisWorkbook.Worksheets
If Not sh Is Application.Caller.Parent Then sheetCol.Add sh
Next
Else
For Each sh In sheetNames
sheetCol.Add Worksheets(sh)
Next
End If
For Each sh In sheetCol
If sh.Range(matchCel.address).Value2 = matchVal Then
If Len(FetchSheets) > 0 Then FetchSheets = FetchSheets & ", "
FetchSheets = FetchSheets & sh.Range(getCel.address).Value2
End If
Next
End Function
To apply it to your example, you can replace your formula with this:
=FetchSheets("y", C23, $C$2, "400", "410", "420")
If you want to fetch from all the sheets except the master, enter this in some master cell:
=FetchSheets("y", C23, $C$2)

Copy a link if cell value matches entry in another list

There is a column with blocks of file names, and there is a column with keys and values:
I have to assign the link "www.111.com" to all AAAAA.jpg areas, "www.222.com" to BBBBB.jpg areas, etc.
Result:
How can be this done?
I think the following VBA code will help you. It does these steps:
Declare a range ("myRange") and set it to cell A1 (the top cell of your list of .JPGs)
Declare a variant ("hText")
Lookup the value in "myRange" in the lookup table at D:E (change to suit your workbook). Store the value in "hText"
Check if hText is an error (i.e., the value was not found in the lookup table). If it was as error, skip the cell. If it wasn't an error, go to step 5.
Add a hyperlink to the current "myRange" cell. Use the hText as the address, use the text of the current "myRange" cell as the displayed text.
Move "myRange" to the next cell down. Loop steps 3-6 until it reaches an empty cell.
Note that the loop will stop when it reaches an empty cell, so if there is a gap in your list it will not reach the bottom. Also, note that any values that are not found in the lookup table will be skipped (no hyperlink added).
Run this code while the sheet with the list of .JPGs is selected.
Sub AddHyperlinks()
Dim myRange As Range
Set myRange = Range("A1")
Dim hText As Variant
Do Until IsEmpty(myRange)
hText = Application.VLookup(myRange.Value, Worksheets("Sheet1").Range("D:E"), 2, False)
If IsError(hText) Then
hText = ""
Else
ActiveSheet.Hyperlinks.Add Anchor:=myRange, Address:=hText, TextToDisplay:=myRange.Text
hText = ""
End If
Set myRange = myRange.Offset(1, 0)
Loop
End Sub

Searching and Returning bold values in VBA

I know that this probably isn't the most ideal way to to do this but just bear with me.
I have a document with a few tables on it. I'm using a userform to search the tables/sub-categories and return the relevant values. I want to select the sub categories with a range of option buttons on a userform, these will in turn set the range for the search function to look within. I also want to dynamically update the option buttons if a new table was to be added or anything along those lines.
The only thing that differentiates the title of a sub-category/table, and the items within it, is that the title of a sub-category/table is bold. So what I'm looking to do is search the first column of the spreadsheet and return the names of any entries in bold. These values are then used to set the names of the option buttons :).
The following function is my attempt at finding the text entities in column a that are in bold, returning them and setting each to an individual variable to be used in another function. The bold1 .... variables are all globally defined variables as I need them in another sub, as is the page variable which contains the relevant page to be used. Currently the code returns an error stating "variable or with block not set" and using the debugger I can see that bold1 .... and all the other boldx variables have no value set. Does anybody know whats going on/how to fix this function.
Thanks in advance :)
Sub SelectBold()
Dim Bcell As Range
For Each Bcell In Worksheets(Page).Range("A1:A500")
If Bcell.Font.Bold = True Then
Set bold1 = Bcell
End If
Next
End Sub
EDIT: I simplified the above function, to remove clutter and help narrow in on the issue. I want the above function to store the contents of the found cell (any cell in the document in bold at this stage) in the variable bold1
This will return an array of values from bold cells in column A of Page.
You can fill a combo or list box with theses values using their list property.
ComboBox1.List = getSubCategories("Sheet1")
Function getSubCategories(Page As String) As String()
Dim arrSubCategories() As String
Dim count As Long
Dim c As Range
With Worksheets(Page)
For Each c In .Range("A2", .Range("A" & Rows.count).End(xlUp))
If c.Font.Bold Then
ReDim Preserve arrSubCategories(count)
arrSubCategories(count) = c.Value
count = count + 1
End If
Next
End With
getSubCategories = arrSubCategories
End Function
you may find useful to have a Range returned with subcategories cells found:
Function SelectBold(Page As String, colIndex As String) As Range
With Worksheets(Page)
With .Range(colIndex & "1", .Cells(.Rows.Count, colIndex).End(xlUp)).Offset(, .UsedRange.Columns.Count)
.FormulaR1C1 = "=if(isbold(RC[-1]),"""",1)"
.Value = .Value
If WorksheetFunction.CountA(.Cells) < .Rows.Count Then Set SelectBold = Intersect(.SpecialCells(xlCellTypeBlanks).EntireRow, .Parent.Columns(1))
.Clear
End With
End With
End Function
Function IsBold(rCell As Range)
IsBold = rCell.Font.Bold
End Function
to be possibly exploited as follows:
Option Explicit
Sub main()
Dim subCategoriesRng As Range, cell As Range
Set subCategoriesRng = SelectBold(Worksheets("bolds").Name, "A") '<--| pass worksheet name and column to search in
If Not subCategoriesRng Is Nothing Then
For Each cell In subCategoriesRng '<--| loop through subcategories cells
'... code
Next cell
End If
End Sub

Subscript Out of Range, even though value is defined

I am writing a piece of code that transfers selected data on an Excel sheet into an array, which is then used to print the data on a new spreadsheet. However, I am getting a "Subscript Out of Range" error, even though a value appears when I scroll over selectArr(i - 1). Here is my code:
Sub Marascuilo()
Dim numRows As Integer 'Number of rows selected
numRows = Selection.Rows.Count
Dim selectArr() As Double 'Array containing numbers from selected cells
selectArr = loadArr(numRows) 'Load values into array
For i = 2 To UBound(selectArr) - LBound(selectArr) + 2
Sheets("Sheet 4").Cells(i, 2).Value = selectArr(i - 1)
Next
End Sub
'This function loads the values from the selected cells into selectArr.
Function loadArr(numRows) As Double()
Dim ResultArray() As Double
r = 1
For Each v In Selection
ReDim Preserve ResultArray(1 To r)
If v <> "" Then
ResultArray(r) = v.Value
r = r + 1
End If
Next
loadArr = ResultArray
End Function
Any ideas as to how I fix this issue?
Thanks!
Jay
Instead of using Sheets("Sheet 4"), you might consider using the sheet's CodeName. If you look in the Project Explorer window, every sheet has a Name and a CodeName. It might look like this
Sheet1 (Sheet1)
Sheet2 (Sheet2)
The first one is the CodeName (can't be changed from the UI). The one in parens is the tab name. Select the sheet in the Project Explorer and press F4 to open the Properties dialog. Go to the (Name) property (a poorly named property) and change it to something meaningful. I change all my sheets' CodeNames and use a wsh prefix. My sheet that's a log has a CodeName of
wshLog
Now I can use wshLog in my code and I get some benefits. The first is that if someone renames the sheet in the UI, the code still works. The second is I can type wshlog (all lower case) and the VBE will change it to wshLog and I get that visual cue that I spelled it right. Finally, my code is more readable, ex wshFinalReport vs. Sheets("Sheet1").