Perform a via VBA added validation in Excel - validation

I have a problem concerning Excel 2010 VBA. I do not know the correct Englisch Excel terms because I use a German Excel Version. But I will try my best. Sorry for that.
In VBA I set a data validation for one cell (a list selection). If the cell has already set a value, it remains in the cell nevertheless it might not fulfill the data validation. Is it possible to perform the just set data validation by VBA and if the validtaion is not fullfilled clear the value in the cell?
Thanks in advance.

Even showing some code would help cross the language barrier and help us answer this question; however, I assume you are asking if you can evaluate the validation itself with VBA code. You can.
The Validation object has a .Value property that can be evaluated:
If Not validation.Value Then
cell.ClearContents
End If

Give this a try:
Sub PlaceDV()
Dim r As Range
Dim v As String
sValid = "alpha,beta,gamma"
Set r = ActiveCell
v = CStr(r.Value)
If InStr(1, sValid, v) = 0 Then
r.ClearContents
End If
With r.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=sValid
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End Sub

Related

Find bottom of a column in Excel using VBScript

I'm writing a script that will extract the contents of a column in an Excel spreadsheet. Since I don't know how many rows will have data, I need to be able to find the end of the column in the course of the script.
In VBA, I would use something like
sht.Range(sht.Cells(row, col), sht.Cells(row, col)).End(xlDown).row
When I tried using that line in the VBScript file (I knew it probably wouldn't work, but I was hoping for some good luck), a message came back saying that 'xlDown' is undefined. I could easily create an Excel macro to do this, but I want the program to run without having to alter the original spreadsheet.
Here's part of my current script where I define the Excel objects
Set fso = CreateObject("Scripting.FileSystemObject")
set xlapp = CreateObject("Excel.Application")
Set wkbk = xlapp.Workbooks.Open(path)
'xlapp.Visible = False
Set sht = wkbk.Sheets(sheetname)
Set myfile = fso.OpenTextFile(txtfile, 2, True)
lrow = sht.Range(sht.Cells(row, col), sht.Cells(row, col)).End(xlDown).row
path, sheetname, and txtfile are previously defined strings, and row and col are previously defined integers.
xlDown is actually a constant. It's value is -4121 as mentioned HERE.
So try something like,
const xlDown = -4121
lrow = sht.Range(sht.Cells(row, col), sht.Cells(row, col)).End(xlDown).row
OR you can make use of xlUp also in the following code to get the rowcount of a column say Column A:
const xlUp = -4162
lrow = sht.Range("A" & sht.Rows.Count).End(xlUp).Row
Glad that it worked. Here is simple one which will give you the count of rows in the used range for sheet sht
lrow = sht.UsedRange.Rows.Count

Modifying an Excel VBA Script to Work in Word

I have the following VBA code:
Sub test2()
Dim w1 As Worksheet
Dim w2 As Worksheet
Dim k As Long
Dim c As Range
Dim d As Range
Dim strFA As String
Set w1 = Sheets("Sheet1")
Set w2 = Sheets("Sheet2")
w2.Cells.Clear
k = 1
With w1.Range("A:A")
Set c = .Cells.Find("FirstThing", After:=.Cells(.Cells.Count), lookat:=xlWhole)
strFA = ""
While Not c Is Nothing And strFA <> c.Address
If strFA = "" Then strFA = c.Address
If IsError(Application.Match(c.Offset(0, 1).value, w2.Range("A:A"), False)) Then
Set d = .Cells.Find("SecondThing", c, , xlWhole)
w2.Range("A" & k).value = c.Offset(1, 0).value
w2.Range("B" & k).value = d.Offset(0, 1).value
k = k + 1
End If
Set c = .Cells.Find("FirstThing", After:=c, lookat:=xlWhole)
Wend
End With
End Sub
The code works essentially like this:
Look through Sheet1 for a certain phrase.
Once the phrase is found, place the value from the cell one row over in Sheet2
Search for a second phrase.
Place the value from the cell one row over in the cell beside the other value in Sheet2
Repeat
Now. I have the same data that, don't ask me why, is in .doc files. I'd like to create something similar to this code that will go through and look for the first phrase, and place the next n characters in an Excel sheet, and then look for the second phrase and place the next m characters in the row beside the cell housing the previous n characters.
I'm not sure whether it's better to do this with a bash script or whether it's possible to do this with VBA, so I've attached both as tags.
Your question seems to be: "I'm not sure whether it's better to do this with a bash script or whether it's possible to do this with VBA"
The answer to that is: You'd need VBA, especially since this is a *.doc file - docx would be a different matter.
In order to figure out what that is, start by trying to do the task manually in Word. More specifically, how to use Word's "Find" functionality. When you get that figured out, record those actions in a macro to get the starting point for your syntax. The code on the Excel side for writing the data across will essentially stay the same.
You'll also need to decide where the code should reside: in Word or in Excel. That will mean researching how to run the other application from within the one you choose - lots of examples here on SO and on the Internet...

Creating a Stacked Column graph

So I've seen a couple posts on this topic, but can't seem to find a way to get it to work. My goal is to create a Stacked Column Graph using VBA with the following characteristics:
Each column is based on data from a row (e.g. E6:P6, E7:P7, etc.).
Each "stack section" is each column in that row (located at E4:P4)
X Axes Labels are located in column A (e.g. A6, A7, etc.)
Y Axes Labels dynamic based on data (non specific).
Chart Title (which is the easy part - I got this).
Granted I also need the legend which shows the color key used by item 2.
This graph is one of three needed per report across 30+ reports that I generated via VBA from a raw data file. The last step to the reports is to make these graphs.
I am able to get stacked graph created, but the biggest problem is that as the data ranges above show, there are gaps in the data. This causes split sections in the graph as well as additional labels that I don't want. Essentially I don't know how to format the graph, and reading the Object Window that pops up from typing "ActiveChart." has only gotten me this far. If I know various formatting commands (alas I'm new to VBA with Excel), I can replicate it across all the charts that I need.
Dim data As Range
Set data = Range("A4:P12")
With Charts.Add
.ChartType = xlColumnStacked
.SetSourceData Source:=data, PlotBy:=xlColumns
.HasTitle = True
.ChartTitle.Text = "Weekly Report"
.Location Where:=xlLocationAsObject, Name:="Sheet1"
End With
Example of what I can make:
Output Graph
Side note about the blank data: The leftmost blank spot where a bar would be is the empty column D. Also I need to be able to edit the axes labels.
How about something like this:
Public Sub MakeGraph()
Dim ws As Excel.Worksheet
Dim data As Excel.Range
Dim x_axis_labels As Excel.Range
Dim series_names As Excel.Range
Dim sh As Excel.Shape
Dim ch As Excel.Chart
Dim I As Long
Set ws = Sheet1
Set data = ws.Range("E4:P12") ' Assumes the data are in E4:P12
Set x_axis_labels = ws.Range("A4:A12") ' Assumes the labels are in A4:A12
Set series_names = ws.Range("E2:P2") ' Assumes the labels are in E2:P2
Set sh = ws.Shapes.AddChart
Set ch = sh.Chart
With ch
.ChartType = xlColumnStacked
.SetSourceData Source:=data, PlotBy:=xlColumns
.HasTitle = True
.ChartTitle.Text = "Weekly Report"
.Axes(xlCategory, xlPrimary).CategoryNames = x_axis_labels
' Add series names
For I = 1 To .SeriesCollection.Count
.SeriesCollection(I).Name = series_names.Cells(1, I)
Next I
End With
Set ch = Nothing
Set sh = Nothing
Set series_names = Nothing
Set x_axis_labels = Nothing
Set data = Nothing
Set ws = Nothing
End Sub
Hope that helps
I take it your missing data would be a column in the range E6:P14? (I'm using E6:P14 because that's what you said first. Your code and #xidgel's later said E4:P12.)
Try this:
Sub MakeChart()
Dim rCats As Range
Dim rNames As Range
Dim rData As Range
Dim iCol As Long
Set rCats = ActiveSheet.Range("A6:A14")
Set rNames = ActiveSheet.Range("E4:P4")
Set rData = ActiveSheet.Range("E6:P14")
With ActiveSheet.Shapes.AddChart(xlColumnStacked).Chart
Do Until .SeriesCollection.Count = 0
.SeriesCollection(1).Delete
Loop
For iCol = 1 To rData.Columns.Count
If WorksheetFunction.Count(rData.Columns(iCol)) > 0 Then
' it's not blank
With .SeriesCollection.NewSeries
.Values = rData.Columns(iCol)
.XValues = rCats
.Name = "=" & rNames.Cells(1, iCol).Address(, , , True)
End With
End If
Next
End With
End Sub

Lotusscript : How to sort the field values (an array of words) by their frequency

I would like to sort the field values (strings) by their frequency in lotusscript.
Has anyone an idea to solve this?
Thanks a lot.
Personally I would avoid LotusScript if you can help it. You are going to run into limitations that cannot be worked around.
Regardless of which route you do take, from a performance point of view it is better to have the View indexes do the work.
So you would create a view. The first column would be as follows.
Column Value: The field you want to check.
Sort: Ascending
Type: Categorized
After this you can access the data using the NotesViewNavigator. The related method call is getNextCategory. This will give you a view entry object which you can call ChildCount on to get totals.
For example (Disclaimer: Code written from memory, not guaranteed to run):
Dim sess As New NotesSession
Dim db As NotesDatabase
Dim vw As NotesView
Dim nav as NotesViewNavigator
Dim entryA As NotesViewEntry
Dim entryB As NotesViewEntry
Set db = sess.CurrentDatabase
Set vw = db.GetView("testView")
vw.AutoUpdate = False
Set nav = vw.CreateViewNav
Set entryA = nav.GetFirst
while entryA not Nothing
Set entryB = nav.GetNextCategory(entryA)
if entryB not nothing then
' Do your processing.
' entryB.childCount will give total.
end if
set EntryA = EntryB
Wend
view.AutoUpdate = True
This way the heavy lifting (string sorting, counting) is handled by the View index. So you only need to process the final results.
To answer the op's (old) question directly, the way to do this in LotusScript is both simple and easy:
dim para as string
dim words as variant
dim fq list as long
'get the text to freq-count
para = doc.text '(or $ from somewhere)
'tidy up para by removing/replacing characters you don't want
para = replace(para, split(". , : ; - [ ] ()"), "")
words = split(para) 'or split(words, "delim") - default is space
forall w in words
if iselement(words(w)) then
fq(w) = fq(w) + 1
Else
fq(w) = 1
End forall
'you now have a count of each individual word in the FQ list
'to get the words out and the word frequencies (not sorted):
forall x in fq
print listtag(x) = x
End forall
Thats it. No issue with LotusScript - quick and easy (and lists can be massive). To get a sorted list, you would have to move to an array and do a sort on it or move to a field and let #sort do the job somehow.

Creating Named Ranges in Excel using Vb Script

I created a code for creating Named Ranges in Excel using Range object but didn't work as it works in VBA. Error comes in the statement where I try to create a Range object, not sure how this could be done.
If anyone could suggest me an idea it would great.
Set Exobj = CreateObject("Excel.Application")
Set Newbook = Exobj.Workbooks.Add()
Newbook.SaveAs("C:\Users\ACER\Desktop\Project Folder\Test17.xlsx")
Exobj.Workbooks.Open("C:\Users\ACER\Desktop\Project Folder\Test17.xlsx")
Exobj.Visible = True
Set Myrange = Exobj.Worksheets(sheets1).Range("A1:H11") ' statement where Error comes
For each C in Myrange
If c.Value = "" Then
C.Value ="Blank"
End if
Next
Exobj.Workbooks.Save()
Exobj.Activeworkbooks.Close()
I think you need to surround sheets1 with quotes, i.e.
Set Myrange = Exobj.Worksheets("sheets1").Range("A1:H11")

Resources