I'm a bit stuck on this one, since I couldn't find much on the web. Basically, I'd like the user to be able to click a button which formats some cells, and then opens a box which makes the user navigate through windows explorer in order to insert one or two pictures in the newly formatted cells.
This is what I have so far:
Private Sub AddPic_Click()
Dim lastCell As Range
Dim newCell1 As Range
Dim newCell2 As Range
Dim newCellMergePic1 As Range
Dim newCellMergePic2 As Range
Dim myRange As Range
Set myRange = Worksheets("Product Packaging").Range("A1:A1000")
For Each r In myRange
If r.MergeCells Then
Set lastCell = r
End If
Next r
Set newCell1 = lastCell.Offset(1, 0)
Set newCell2 = newCell1.Offset(0, 5)
Set newCellMergePic1 = Range(newCell1, newCell1.Offset(9, 4))
Set newCellMergePic2 = Range(newCell2, newCell2.Offset(9, 4))
newCellMergePic1.Merge
newCellMergePic2.Merge
With newCellMergePic1
.Font.Name = "Calibri"
.Font.Color = vbBlack
.VerticalAlignment = xlVAlignCenter
.HorizontalAlignment = xlHAlignCenter
.Font.Bold = True
.Value = "Picture Here"
End With
With newCellMergePic2
.Font.Name = "Calibri"
.Font.Color = vbBlack
.VerticalAlignment = xlVAlignCenter
.HorizontalAlignment = xlHAlignCenter
.Font.Bold = True
.Value = "Picture Here"
End With
End Sub
It works, but I don't know how to integrate the feature which allows the user to navigate through their folders in order to select the picture(s) they want to add. Thank you for the taking the time to read my post.
You will need to use a dialog box:
Option Explicit
Public Sub addImage1()
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.ButtonName = "Ok"
.Title = "Select an image"
.Filters.Clear
.Filters.Add "JPG", "*.JPG"
.Filters.Add "JPEG File Interchange Format", "*.JPEG"
.Filters.Add "Graphics Interchange Format", "*.GIF"
.Filters.Add "Portable Network Graphics", "*.PNG"
.Filters.Add "All Pictures", "*.*"
If .Show = -1 Then
Dim img As Object
Set img = ActiveSheet.Pictures.Insert(.SelectedItems(1))
Else
MsgBox ("Cancelled.")
End If
End With
End Sub
or
Public Sub addImage2()
Dim result, imgTypes As String
imgTypes = imgTypes & "JPG files (*.jp*),*.jp*"
imgTypes = imgTypes & ", GIF files (*.gif),*.gif"
imgTypes = imgTypes & ", PNG files (*.png),*.png"
imgTypes = imgTypes & ", All files (*.*),*.*"
result = Application.GetOpenFilename(imgTypes, 1, "Select Image", , False)
If result <> False Then
ActiveSheet.Pictures.Insert (result)
End If
End Sub
Problem solved, here is the final result
Private Sub AddPic_Click()
Dim lastCell As Range
Dim newCell1 As Range
Dim newCell2 As Range
Dim newCellMergePic1 As Range
Dim newCellMergePic2 As Range
Dim myRange As Range
Dim fd As Office.FileDialog
Dim Pic1 As Picture
Dim Pic2 As Picture
Dim Pic1Path As String
Dim Pic2Path As String
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Set myRange = Worksheets("Product Packaging").Range("A1:A1000")
For Each r In myRange
If r.MergeCells Then
Set lastCell = r
End If
Next r
Set newCell1 = lastCell.Offset(1, 0)
Set newCell2 = newCell1.Offset(0, 5)
Set newCellMergePic1 = Range(newCell1, newCell1.Offset(9, 4))
Set newCellMergePic2 = Range(newCell2, newCell2.Offset(9, 4))
newCellMergePic1.Merge
newCellMergePic2.Merge
With newCellMergePic1
.Font.Name = "Calibri"
.Font.Color = vbBlack
.VerticalAlignment = xlVAlignCenter
.HorizontalAlignment = xlHAlignCenter
.Font.Bold = True
.Value = "Picture Here"
End With
With newCellMergePic2
.Font.Name = "Calibri"
.Font.Color = vbBlack
.VerticalAlignment = xlVAlignCenter
.HorizontalAlignment = xlHAlignCenter
.Font.Bold = True
.Value = "Picture Here"
End With
With fd
.AllowMultiSelect = True
.Title = "Please select picture(s). Maximum of two pictures per insert."
.Filters.Add "Images", "*.gif; *.jpg; *.jpeg", 1
If .Show = True Then
If .SelectedItems.Count > 2 Then
MsgBox "Please select no more than 2 pictures at once.", vbExclamation, Conflict
Dim delRange1 As Excel.Range
Dim delRange2 As Excel.Range
Set myRange = Worksheets("Product Packaging").Range("A1:A1000")
For Each r In myRange
If r.MergeCells Then
Set lastCell = r
End If
Next r
If lastCell.Address <> Range("A2").Address Then
Set lastCell2 = lastCell.Offset(0, 5)
Set delRange1 = lastCell.MergeArea
Set delRange2 = lastCell2.MergeArea
delRange1.ClearContents
delRange2.ClearContents
lastCell.UnMerge
lastCell2.UnMerge
Exit Sub
End If
End If
Pic1Path = .SelectedItems(1)
Set Pic1 = Pictures.Insert(Pic1Path)
With Pic1.ShapeRange
.LockAspectRatio = msoTrue
.Height = newCellMergePic1.Height - 2
.Top = newCellMergePic1.Top + 1
.Left = newCellMergePic1.Left
End With
If .SelectedItems.Count = 2 Then
Pic2Path = .SelectedItems(2)
Set Pic2 = Pictures.Insert(Pic2Path)
With Pic2.ShapeRange
.LockAspectRatio = msoTrue
.Height = newCellMergePic2.Height - 2
.Top = newCellMergePic2.Top + 1
.Left = newCellMergePic2.Left
End With
End If
End If
End With
End Sub
Related
We have 4 Html pages that we are joining together into 1 file.
For the first page, we are reading a blank PDF file (letter head) to add as the background and then add the further 3 pages.
However, all seemed ok in version 8, but now the second page will not show.
thedoc reads the blank pdf and then the html page which overlays the text no issue here.
thedoc1 is the second page which will not load
thedoc1a and thedoc2 load ok.
If I remove the adding of the letter head from thedoc, then all 4 pages load ok, but as soon as I try and use the letter head, the second page doesnt load.
Ive added my script below. What I am doing wrong please
Sub page_load()
Dim rs
Dim strSQLQuery As String
Dim theDoc As Doc = New Doc()
Dim theDoc1 As Doc = New Doc()
Dim theDoc1a As Doc = New Doc()
Dim theDoc2 As Doc = New Doc()
Dim theDoccontents As Doc = New Doc()
theDoc.MediaBox.String = "A4"
theDoc1.MediaBox.String = "A4"
theDoc1a.MediaBox.String = "A4"
theDoc2.MediaBox.String = "A4
theDoc.HtmlOptions.PageCacheEnabled = False
theDoc.HtmlOptions.PageCacheClear()
theDoc.HtmlOptions.ImageQuality = 33
theDoc1.HtmlOptions.ImageQuality = 33
theDoc1a.HtmlOptions.ImageQuality = 33
theDoc2.HtmlOptions.ImageQuality = 33
theDoc.HtmlOptions.AddLinks = True
theDoc1.HtmlOptions.AddLinks = True
theDoc1a.HtmlOptions.AddLinks = True
theDoc2.HtmlOptions.AddLinks = True
theDoc.HtmlOptions.Timeout = 10000000
theDoc1.HtmlOptions.Timeout = 10000000
theDoc1a.HtmlOptions.Timeout = 10000000
theDoc2.HtmlOptions.Timeout = 10000000
Dim rbrandchosen As String
Dim quotenumber As String
Dim rnum As String
Dim cover as string
dim pagex as integer
quotenumber=request("quotenumber")
rbrandchosen=request("rbrandchosen")
response.write(quotenumber)
Dim theURL As String
Dim theID As Integer
Dim strsql as string
Dim theSection as string
Dim theCountDoc1a As Integer
Randomize()
rnum = (CInt(Math.Floor(90 * Rnd())) + 10).ToString
' add covering letter
cover = "c:\\inetpub\\wwwroot\\icopalukintranet\\pnf\\letterhead.pdf"
theDoc.Read(cover)
'theID = theDoc.AddObject("<< >>")
theDoc.HtmlOptions.UseScript = True
theDoc.HtmlOptions.Engine = EngineType.Chrome86
' Render after 2 seconds
theDoc.Rect.SetRect(20, 110, 600, 620)
theDoc.HtmlOptions.OnLoadScript = "(function(){ window.ABCpdf_go = false; setTimeout(function(){ window.ABCpdf_go = true; }, 3000); })();"
theURL = "http://localhost/icopalukintranet/pnf/rooflights/rooflightquotepdfletter.asp?quotenumber="+ quotenumber + "&stridrnd="+rnum
'theDoc.AddImageUrl(theURL)
theID = theDoc.AddImageUrl(theURL)
While True
If Not theDoc.Chainable(theID) Then
Exit While
End If
theDoc.Page = theDoc.AddPage()
theID = theDoc.AddImageToChain(theID)
End While
' add quote
theDoc1.HtmlOptions.Engine = EngineType.Chrome86
theDoc1.HtmlOptions.UseScript = True
theDoc1.Rect.SetRect(0, 0, 600, 820)
' Render after 2 seconds
theDoc1.HtmlOptions.OnLoadScript = "(function(){ window.ABCpdf_go = false; setTimeout(function(){ window.ABCpdf_go = true; }, 2000); })();"
theURL = "http://localhost/icopalukintranet/pnf/rooflights/rooflightquotepdfquote.asp?quotenumber="+ quotenumber + "&stridrnd="+rnum
theDoc1.Page = theDoc1.AddPage()
theID = theDoc1.AddImageUrl(theURL)
While True
If Not theDoc1.Chainable(theID) Then
Exit While
End If
theSection = "Quote"
theDoc1.Page = theDoc1.AddPage()
theID = theDoc1.AddImageToChain(theID)
theDoc1.AddBookmark(theSection, True)
End While
' add notes
theDoc1a.HtmlOptions.Engine = EngineType.Chrome86
theDoc1a.HtmlOptions.UseScript = True
theDoc1a.Rect.SetRect(0, 0, 600, 820)
' Render after 3 seconds
theDoc1a.HtmlOptions.OnLoadScript = "(function(){ window.ABCpdf_go = false; setTimeout(function(){ window.ABCpdf_go = true; }, 1000); })();"
theURL = "http://localhost/icopalukintranet/pnf/rooflights/rooflightquotepdfnotes.asp?quotenumber="+ quotenumber + "&stridrnd="+rnum
theDoc1a.Page = theDoc1a.AddPage()
theID = theDoc1a.AddImageUrl(theURL)
While True
If Not theDoc1a.Chainable(theID) Then
Exit While
End If
theDoc1a.Page = theDoc1a.AddPage()
theID = theDoc1a.AddImageToChain(theID)
End While
' add terms details
theDoc2.HtmlOptions.Engine = EngineType.Chrome86
theDoc2.HtmlOptions.UseScript = True
theDoc2.Rect.SetRect(20, 80, 560, 710)
theDoc2.Transform.Magnify(0.93 ,0.93, 0, 690)
' Render after 1 seconds
theDoc2.HtmlOptions.OnLoadScript = "(function(){ window.ABCpdf_go = false; setTimeout(function(){ window.ABCpdf_go = true; }, 2000); })();"
theURL = "http://localhost/icopalukintranet/pnf/rooflights/rooflightquotepdfterms.asp?quotenumber="+ quotenumber + "&stridrnd="+rnum
theDoc2.Page = theDoc2.AddPage()
theID = theDoc2.AddImageUrl(theURL)
While True
If Not theDoc2.Chainable(theID) Then
Exit While
End If
theSection = "Terms"
theDoc2.Page = theDoc2.AddPage()
theID = theDoc2.AddImageToChain(theID)
theDoc2.AddBookmark(theSection, True)
End While
Dim cst = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Server.MapPath("rooflightquotes.mdb")
Dim conn = CreateObject("ADODB.Connection")
conn.open(cst)
Session("myConn") = conn
dim rsAddquestion = Server.CreateObject("ADODB.Recordset")
strsql ="select * from pdfs where id=" & quotenumber & " "
rsAddquestion.Open(strsql, conn, 3, 3)
dim n as string
n=rsAddquestion.recordcount
rsAddquestion.AddNew
n=n+1
rsAddquestion("id")=quotenumber
rsAddquestion("pdfname") =quotenumber +"-rev"+n+".pdf"
rsAddquestion("printdate")=now()
rsAddquestion("status")="Printed"
rsAddquestion.update
rsAddquestion = Server.CreateObject("ADODB.Recordset")
strsql ="select * from header where id=" & quotenumber & " "
rsAddquestion.Open(strsql, conn, 3, 3)
rsAddquestion("status")="Printed"
rsAddquestion.update
conn.close
' add the pdf together in selected order
theDoc.Append(theDoc1)
theDoc.Append(theDoc1a)
theDoc.Append(theDoc2)
Dim theCount = theDoc.PageCount
' left bottom width heght
theDoc.Rect.String = "10 10 580 25"
theDoc.HPos = 1.0
theDoc.VPos = 0.5
theDoc.Color.String = "255 255 255"
theDoc.Font = theDoc.AddFont("Arial")
theDoc.FontSize = 10
For i = 1 To theCount
theDoc.PageNumber = i
If i <> 1 Then
theDoc.AddHtml(" Page " + i.ToString() + " of " + theCount.ToString() + "")
theDoc.FrameRect()
End If
Next
dim pdffilenamec = "pdf/"+quotenumber+"-rev"+n+".pdf"
theDoc.Save(Server.MapPath(pdffilenamec))
'response.redirect("rooflightquotepdfmenu.asp?quotenumber="+quotenumber)
End Sub
This used to work find in version 8, but not now using version 12
I am learning through the internet and based on my knowledge and data available on the internet, I have created the following macro which works. The purpose of the macro is to filter the data, arrange it in the desired format and print it.
The problem is, once I run the macro, all the filters are printed in one pass. I am looking for a change where after running the macro, I get a display to select the filter I want to print or if I want to print all the filters.
I hope I was able to explain my problem. Let me know if anyone can help me. Thanks
Sub itemno()
ThisWorkbook.Worksheets("Sheet1").Activate
Dim LR As Long
Dim Sh As Worksheet
Set Sh = Worksheets("Sheet1")
LR = Sh.Range("H" & Rows.Count).End(xlUp).Row
Sh.Range("P2:P" & LR).Formula = "=IF(LEFT(RC[-13],3)=""300"",RIGHT(RC[-7],4)&""-""&RIGHT(RC[-14],3),RC[-13])"
Sh.Range("P1:P" & LR).Copy
Sh.Columns("B:B").Select
Selection.PasteSpecial Paste:=xlPasteValues
Sh.Columns("C:C").Delete
Sh.Columns("F:F").Delete
Sh.Columns("I:P").Delete
Sh.Range("A1").FormulaR1C1 = "Colli Nr."
Sh.Range("B1").FormulaR1C1 = "Item Nr."
Sh.Range("D1").FormulaR1C1 = "Unit"
Sh.Cells.Select
Sh.Cells.EntireColumn.Autofit
Sh.Columns("A:A").ColumnWidth = 20
Sh.Columns("C:C").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlTop
End With
Selection.NumberFormat = "0.0"
Sh.Cells.Select
Selection.RowHeight = 25
With Selection
.VerticalAlignment = xlCenter
End With
Sh.Rows("1:1").Select
With Selection.Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Sh.Columns("F:F").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Sh.Range("F1").Select
ActiveCell.FormulaR1C1 = "Bemerkung"
Sh.Rows("1:1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With
Selection.Font.Bold = True
With Selection.Font
.Name = "Arial"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
.TintAndShade = 0
.ThemeFont = xlThemeFontNone
End With
Sh.Columns("E:E").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Sh.Range("E1").FormulaR1C1 = "CheckBox"
Sh.Range("M2:M" & LR).Formula = "=RC[-10]&"" ""&RC[-9]"
Sh.Range("M1:M" & LR).Copy
Sh.Columns("C:C").Select
Selection.PasteSpecial Paste:=xlPasteValues
Sh.Range("C1").FormulaR1C1 = "Menge"
Sh.Columns("M:M").Delete
Sh.Columns("D:D").Delete
Dim cb As CheckBox
Dim myRange As Range, cel As Range
Dim wks As Worksheet
Set wks = Sheets("Sheet1")
Set myRange = wks.Range("D2:D" & LR)
For Each cel In myRange
Set cb = wks.CheckBoxes.Add(cel.Left, cel.Top, 30, 15)
With cb
.Caption = ""
.OnAction = "ProcessCheckBox"
End With
Next
Dim Rang As Range
Set Rang = Sh.Range("A1:I" & LR)
With Rang.Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
wks.Rows("1:7").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.RowHeight = 15
Sh.Range("A1:F1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Selection.Merge
Sh.Range("A1:F1").Select
ActiveCell.FormulaR1C1 = "Packliste nur für die Werkstatt"
Sh.Range("A3").Select
ActiveCell.FormulaR1C1 = "Projekt:"
Sh.Range("B3:D3").Select
With Selection
.HorizontalAlignment = xlLeft
End With
Selection.Merge
Sh.Range("E3").Select
ActiveCell.FormulaR1C1 = "Column Nr."
Sh.Range("A4").Select
ActiveCell.FormulaR1C1 = "Zeichnung Nr. "
Sh.Range("B4:C4").Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Selection.Merge
Sh.Range("E4").Select
ActiveCell.FormulaR1C1 = "Dokument Nr."
Sh.Range("A6").Select
ActiveCell.FormulaR1C1 = "Verpackt von:"
Sh.Range("E6").Select
ActiveCell.FormulaR1C1 = "Geprüft von:"
Sh.Rows("1:1").Select
Selection.RowHeight = 20
Selection.Font.Bold = True
Selection.Font.Size = 16
Selection.Font.Underline = xlUnderlineStyleSingle
Sh.Columns("B:B").ColumnWidth = 20
Sh.Columns("D:D").ColumnWidth = 15
Sh.Columns("C:C").ColumnWidth = 12
Sh.Columns("F:F").ColumnWidth = 40
Sh.Columns("G:G").Cut
Sh.Columns("J:J").Insert Shift:=xlToRight
Sh.Activate
Dim Rng As Range
Dim c As Range
Dim List As New Collection
Dim Item As Variant
Application.ScreenUpdating = False
Set Rng = Sh.Range("G9:G" & Sh.Range("G65536").End(xlUp).Row)
On Error Resume Next
For Each c In Rng
List.Add c.Value, CStr(c.Value)
Next c
On Error GoTo 0
Set Rng = Sh.Range("G8:G" & Sh.Range("G65536").End(xlUp).Row)
For Each Item In List
Rng.AutoFilter Field:=1, Criteria1:=Item
Sh.Range("F4") = Item
Sh.Range("F3:F4").Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlCenter
End With
Sh.Range("F3").FormulaR1C1 = "=VLOOKUP(TEXT(R[1]C,0),C[1]:C[3],3,FALSE)"
Sh.Range("B4:C4").FormulaR1C1 = "=VLOOKUP(TEXT(RC[4],0),C[5]:C[7],2,FALSE)"
Sh.Range("B3:D3").FormulaR1C1 = "=LEFT(R[6]C,9)"
Application.PrintCommunication = False
Sh.Activate
ActiveSheet.PageSetup.PrintArea = "$A:$F"
With ActiveSheet.PageSetup
.PrintTitleRows = "$1:$8"
.LeftMargin = Application.InchesToPoints(0.236220472440945)
.RightMargin = Application.InchesToPoints(0.236220472440945)
.TopMargin = Application.InchesToPoints(0.2)
.BottomMargin = Application.InchesToPoints(0.35)
.HeaderMargin = Application.InchesToPoints(0.2)
.FooterMargin = Application.InchesToPoints(0.35)
.Orientation = xlLandscape
.PaperSize = xlPaperA4
.LeftFooter = "Colli-Informationen eingeben (Abmessungen, Bruttogewicht & Tara)"
.RightFooter = "&P/&N"
End With
Application.PrintCommunication = True
Sh.PrintOut
Rng.AutoFilter
Next Item
Application.ScreenUpdating = True
End Sub
I have a script which copies the values of columns A and B to column A and B of another Excel. Column headers are same.
What I want is to lookup from first Excel value of Column A in the second Excel and if there is a match then get the value of corresponding
value of Column B in the same row and paste it in the first Excel. If there is no match, then insert #N/A in column B of first Excel.
There should be no change to second Excel(where we look up the value). Colummn B in the first Excel is empty.
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open("C:\TEST.xlsx")
Set objWorkbook2 = objExcel.Workbooks.Open("C:\Desktop\IPT\Test.xlsx")
'objExcel.DisplayAlerts = False
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Activate
Set objRange = objWorkSheet.Range("A:B").EntireColumn
objWorkSheet.Range("A:B").EntireColumn.Copy
Set objWorksheet2 = objWorkbook2.Worksheets(1)
objWorksheet.Activate
Set objRange = objWorkSheet2.Range("A:B")
objWorkSheet2.Paste objWorkSheet2.Range("A:B")
objWorksheet2.Paste(objRange)
objworkbook2.Save
objWorkbook.close("C:\TEST.xlsx")
objWorkbook2.close("C:\Desktop\IPT\Test.xlsx")
objExcel.Quit
objExcel.DisplayAlerts = True
Here is the first Excel
A B C
101 12
102 13
103 15
Second Excel File
A B C
101 Toy1 small
102 Toy2 medium
103 Toy3 high
Updated code:
ProcessFiles()
Sub ProcessFiles()
Const xlUp = -4162
Const vbCritical = 16
Const BOOK1 = "C:\TEST.xlsx.xls"
Const BOOK2 = "C:\Desktop\IPT\Test.xlsx"
Dim xlApp, xlWB, dict, r
Set dict = CreateObject("Scripting.Dictionary")
Set xlApp = CreateObject("Excel.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(BOOK1) Then
MsgBox BOOK1 & " not found", vbCritical
Exit Sub
ElseIf objFSO.FolderExists(BOOK2) Then
MsgBox BOOK2 & " not found", vbCritical
Exit Sub
End If
Set objFSO = Nothing
Set xlWB = xlApp.Workbooks.Open(BOOK2)
With xlWB.Worksheets(1)
For Each r In .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
If Not dict.Exists(r.Text) Then dict.Add r.Text, r.Offset(0, 1).Value
Next
End With
xlWB.Close False
Set xlWB = xlApp.Workbooks.Open(BOOK1)
With xlWB.Worksheets(1)
For Each r In .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
'r.Offset(0, 4) = IIf(dict.Exists(r.Text), dict(r.Text), "#N/A")
If dict.Exists(r.Text) Then
r.Offset(0, 4) = dict(r.Text)
Else
r.Offset(0, 4) = "#N/A"
End If
Next
End With
xlWB.Close True
End Sub
Scripting Dictionaries make it easy to compare lists.
Sub ProcessFiles()
Const xlUp = -4162
Const vbCritical = 16
Const BOOK1 = "\\norfile5\Public\Table Games\Spotlights\Back Up\SO\Book1.xlsx"
Const BOOK2 = "\\norfile5\Public\Table Games\Spotlights\Back Up\SO\Book2.xlsx"
Dim xlApp, xlWB, dict, r
Set dict = CreateObject("Scripting.Dictionary")
Set xlApp = CreateObject("Excel.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(BOOK1) Then
MsgBox BOOK1 & " not found", vbCritical
Exit Sub
ElseIf objFSO.FolderExists(BOOK2) Then
MsgBox BOOK2 & " not found", vbCritical
Exit Sub
End If
Set objFSO = Nothing
Set xlWB = xlApp.Workbooks.Open(BOOK2)
With xlWB.Worksheets(1)
For Each r In .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
If Not dict.Exists(r.Text) Then dict.Add r.Text, r.Offset(0, 1).Value
Next
End With
xlWB.Close False
Set xlWB = xlApp.Workbooks.Open(BOOK1)
With xlWB.Worksheets(1)
For Each r In .Range("A2", .Range("A" & .Rows.Count).End(xlUp))
If dict.Exists(r.Text) then
r.Offset(0, 1) = dict(r.Text)
Else
r.Offset(0, 1) = "#N/A"
End If
Next
End With
xlWB.Save
xlWB.Close False
xlApp.Quit
Msgbox BOOK1 & " has been updated"
End Sub
I can think of two ways to do this.
Create a system to organize your data into arrays, then use several simple algorithms to slide things into place. This would require parsing cell by cell to retrieve the data.
I prefer this method as it has potential to be quite abstract as a program in itself. I also highly suggest using arraylists if you do it.
Insert VLookup() functions into your Book1: Column B cells
I believe this would be more tedious...
i m using asp classic. i want to rename image file while i upload image on web folder created by me. please help me out of this issue.
If there is a file in targeted folder with same name (like lokesh.jpg) what i am uploading, than new file should b automatically renamed(like lokesh(1).jpg) instead of overwriting
my code is as below:
upload.asp
<%
Class FileUploader
Public Files
Private mcolFormElem
Private Sub Class_Initialize()
Set Files = Server.CreateObject("Scripting.Dictionary")
Set mcolFormElem = Server.CreateObject("Scripting.Dictionary")
End Sub
Private Sub Class_Terminate()
If IsObject(Files) Then
Files.RemoveAll()
Set Files = Nothing
End If
If IsObject(mcolFormElem) Then
mcolFormElem.RemoveAll()
Set mcolFormElem = Nothing
End If
End Sub
Public Property Get Form(sIndex)
Form = ""
If mcolFormElem.Exists(LCase(sIndex)) Then Form = mcolFormElem.Item(LCase(sIndex))
End Property
Public Default Sub Upload()
Dim biData, sInputName
Dim nPosBegin, nPosEnd, nPos, vDataBounds, nDataBoundPos
Dim nPosFile, nPosBound
biData = Request.BinaryRead(Request.TotalBytes)
nPosBegin = 1
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(13)))
If (nPosEnd-nPosBegin) <= 0 Then Exit Sub
vDataBounds = MidB(biData, nPosBegin, nPosEnd-nPosBegin)
nDataBoundPos = InstrB(1, biData, vDataBounds)
Do Until nDataBoundPos = InstrB(biData, vDataBounds & CByteString("--"))
nPos = InstrB(nDataBoundPos, biData, CByteString("Content-Disposition"))
nPos = InstrB(nPos, biData, CByteString("name="))
nPosBegin = nPos + 6
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(34)))
sInputName = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
nPosFile = InstrB(nDataBoundPos, biData, CByteString("filename="))
nPosBound = InstrB(nPosEnd, biData, vDataBounds)
If nPosFile <> 0 And nPosFile < nPosBound Then
Dim oUploadFile, sFileName
Set oUploadFile = New UploadedFile
nPosBegin = nPosFile + 10
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(34)))
sFileName = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
oUploadFile.FileName = Right(sFileName, Len(sFileName)-InStrRev(sFileName, "\"))
Dim oFileExtension
If sFileName <> "" then
oFileExtension = (Right(sFileName, Len(sFileName)-InStrRev(sFileName, ".")))
If oFileExtension <> "jpg" AND oFileExtension <> "jpeg" AND oFileExtension <> "gif" AND oFileExtension <> "pdf" then
response.write("<h1>Post New File</h1><p><font color=#ff0000>An error has occurred while processing your request.<br><br>We are sorry, Extensions other than JPG, JPEG, Gif, PDF are not allowed to upload<p><b>Click <a href='javascript:history.go(-1);'>here</a> to go back and address the error.</b></font>")
response.end
Exit Sub
End if
end If
nPos = InstrB(nPosEnd, biData, CByteString("Content-Type:"))
nPosBegin = nPos + 14
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(13)))
oUploadFile.ContentType = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
nPosBegin = nPosEnd+4
nPosEnd = InstrB(nPosBegin, biData, vDataBounds) - 2
oUploadFile.FileData = MidB(biData, nPosBegin, nPosEnd-nPosBegin)
If sfileName <> "" then
If oUploadFile.FileSize > 10000000 Then
response.write("<h1>Post New Image</h1><p><font color=#ff0000>An error has occurred while processing your request.<br><br>We are sorry, Upload file containing 10000000(10mb) bytes only.<p><b>Click <a href='javascript:window:history.go(-1);'>here</a> to go back and address the error.</b></font>")
response.end
Exit Sub
End if
End if
If oUploadFile.FileSize > 0 Then Files.Add LCase(sInputName), oUploadFile
Else
nPos = InstrB(nPos, biData, CByteString(Chr(13)))
nPosBegin = nPos + 4
nPosEnd = InstrB(nPosBegin, biData, vDataBounds) - 2
If Not mcolFormElem.Exists(LCase(sInputName)) Then mcolFormElem.Add LCase(sInputName), CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
End If
nDataBoundPos = InstrB(nDataBoundPos + LenB(vDataBounds), biData, vDataBounds)
Loop
End Sub
'String to byte string conversion
Private Function CByteString(sString)
Dim nIndex
For nIndex = 1 to Len(sString)
CByteString = CByteString & ChrB(AscB(Mid(sString,nIndex,1)))
Next
End Function
'Byte string to string conversion
Private Function CWideString(bsString)
Dim nIndex
CWideString =""
For nIndex = 1 to LenB(bsString)
CWideString = CWideString & Chr(AscB(MidB(bsString,nIndex,1)))
Next
End Function
End Class
Class UploadedFile
Public ContentType
Public FileName
Public FileData
Public Property Get FileSize()
FileSize = LenB(FileData)
End Property
Public Sub SaveToDisk(sPath)
Dim oFS, oFile
Dim nIndex
If sPath = "" Or FileName = "" Then Exit Sub
If Mid(sPath, Len(sPath)) <> "\" Then sPath = sPath & "\"
Set oFS = Server.CreateObject("Scripting.FileSystemObject")
If Not oFS.FolderExists(sPath) Then Exit Sub
Set oFile = oFS.CreateTextFile(sPath & FileName, True)
For nIndex = 1 to LenB(FileData)
oFile.Write Chr(AscB(MidB(FileData,nIndex,1)))
Next
oFile.Close
End Sub
Public Sub SaveToDatabase(ByRef oField)
If LenB(FileData) = 0 Then Exit Sub
If IsObject(oField) Then
oField.AppendChunk FileData
End If
End Sub
End Class
%>
submit.asp
<!-- #include file="upload.asp" -->
<%
response.buffer = true
Dim Uploader, File, i, j
Set Uploader = New FileUploader
Uploader.Upload()
Dim brandnm, filename
brandnm = Uploader.form("brandname")
Dim objRSa, objCmda, stra
Set objCmda = server.CreateObject("adodb.connection")
Set Objrsa = Server.CreateObject("ADODB.Recordset")
objCmda.open MM_connDUdirectory_STRING
stra = "SELECT * FROM brand"
Objrsa.Open stra,objCmda,1,2
if Uploader.Files.count <> 0 then
File = Uploader.Files.Items()
File(0).SavetoDisk Server.MapPath("upload/brands") 'Folder path where image will save
filename = File(0).Filename
else
filename = ""
End if
Objrsa.addnew
Objrsa.fields("brand_name") = brandnm
Objrsa.fields("brand_createddt") = now()
if filename <>"" then Objrsa.fields("brand_picpath") = filename
For Each File In Uploader.Files.Items
Objrsa("brand_ctype") = File.ContentType
next
Objrsa.Update
Objrsa.Close
Set Objrsa = Nothing
set objCmda = Nothing
%>
Please help me out of this issue.
If you want to rename it to follow a known pattern as in your example ("filename(number).ext"), you must to use a pseudo-code like this:
let counter = 1
let original = file(0).Filename
let current = file(0).Filename
while(current file exists)
current = original-without-extension + (counter) + original-extension
counter = counter + 1
end
However, I think that would be better to store the user provided filename into your database and choose a random-like filename to store the actual file into the filesystem.
let current = userLogin + (currentTime as yyyyMMddHHmmss) + ".uploaded"
By using a bogus file extension you make your application way more secure, as your file will not be interpretable/executable -- imagine a malicious user uploading an .ASP file and executing it.
If this break the image MIME type, you should consider creating another .ASP page read the database to discover the appropriate MIME type based on the user provided file extension, write that content-type and the binary file content.
TL;DR: don't use the user provided file name, create a new one. This will avoid server hacking.
I have an auto-filtered range of data. The auto filter was created by the following VB code:
Sub Colour_filter()
Range("A4").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Selection.AutoFilter
End Sub
I would like to sort the values in column "A" (the data actually start from cell "A4") by the following colour ( Color = RGB(255, 102, 204) ) so all the cells with that colour sort to the top.
It would be fab if the extra code could be added to my existing code?
My office is really noisy and my VB isn’t the best. It is doubly hard with laughing, chatting ladies all about. Any help will be stress relief heaven!! (p.s. no poke at the ladies it’s just my office is 95% women).
Edited per request by #ScottHoltzman.
My requested code forms part of a larger code which would confuse matters, although here is a slimmed down version of the aspect I currently need.
Sub Colour_filter()
' Following code( using conditional formatting) adds highlight to 'excluded' courses based
'on 'course code' cell value matching criteria. Courses codes matching criteria are highlighted
'in 'Pink'; as of 19-Nov-2012 the 'excluded' course codes are
'(BIGTEST, BIGFATCAT).
' <====== CONDITIONAL FORMATTING CODE STARTS HERE =======>
Columns("A:A").Select
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=""BIGTEST"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.Color = 13395711
End With
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=""BIGFATCAT"""
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.Color = 13395711
End With
' <====== CONDITIONAL FORMATTING CODE ENDS HERE =======>
' Following code returns column A:A to Font "Tahoma", Size "8"
Columns("A:A").Select
With Selection.Font
.Name = "Tahoma"
.FontStyle = "Regular"
.Size = 8
.ThemeColor = xlThemeColorLight1
.ThemeFont = xlThemeFontNone
End With
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlTop
.WrapText = False
End With
' Following code adds border around all contiguous cells ion range, similar to using keyboard short cut "Ctrl + A".
Range("A4").Select
ActiveCell.CurrentRegion.Select
With Selection
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
End With
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlThin
End With
' Following code adds 'Blue' cell colour to all headers in Row 4 start in Cell "A4".
Range("A4").Select
Range(Selection, Selection.End(xlToRight)).Select
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlTop
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorLight2
.TintAndShade = 0.399975585192419
.PatternTintAndShade = 0
End With
With Selection.Font
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
Selection.Font.Bold = True
'<== adds auto-filter to my range of cells ===>
Range("A4").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Selection.AutoFilter
End Sub
Well here is a small Sub that does the following sorting as per shown image. Most of the values like dimensions/range sizes are very static since this is a sample. You may improve it to be dynamic. Please comment if this code is going in the right direction so I can update with the final sort.
EDITTED CODE WITH DOUBLE SORT KYES
code:
Option Explicit
Sub sortByColor()
Dim rng As Range
Dim i As Integer
Dim inputArray As Variant, colourSortID As Variant
Dim colourIndex As Long
Set rng = Sheets(1).Range("D2:D13")
colourIndex = Sheets(1).Range("G2").Interior.colorIndex
ReDim inputArray(1 To 12)
ReDim colourSortID(1 To 12)
For i = 1 To 12
inputArray(i) = rng.Cells(i, 1).Interior.colorIndex
If inputArray(i) = colourIndex Then
colourSortID(i) = 1
Else
colourSortID(i) = 0
End If
Next i
'--output the array with colourIndexvalues and sorting key values
Sheets(1).Range("E2").Resize(UBound(inputArray) + 1) = _
Application.Transpose(inputArray)
Sheets(1).Range("F2").Resize(UBound(colourSortID) + 1) = _
Application.Transpose(colourSortID)
'-sort the rows based on the interior colour
Application.DisplayAlerts = False
Set rng = rng.Resize(, 3)
rng.Sort Key1:=Range("F2"), Order1:=xlDescending, _
Key2:=Range("E2"), Order1:=xlAscending, Header:=xlNo, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
Application.DisplayAlerts = True
End Sub
output: